<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\User;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;
use app\admin\model\Common;
use app\admin\model\ShopRefundOrderModel;
use think\response\Json;
use think\Validate;
use app\crm\logic\WhereLogic;
use app\crm\model\CustomerInfoAPI as CustomerInfoAPIModel;//引用EC接口文档

class Customer extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';

	public function shopRefundOrder()
	{
	    return $this->hasMany(ShopRefundOrderModel::class, 'uid','id');
	}

    public function nurse(){
        return $this->hasOne(ShopPerson::class,'id','nurse_id');
    }

    // 获取客户的余额
    public function getCustomerBalance($customer_id,$business_type){

        $balanceList = Db::name('customer_balance')
            ->where([['customer_id','=',$customer_id]])
            ->column('money,complimentary_money,shop_transfer_money','balance_category_id');
        $money               = $balanceList[$business_type]['money'] ?? 0; // 获取用户余额
        $complimentary_money = $balanceList[$business_type]['complimentary_money'] ?? 0; // 获取用户赠金
        $shop_transfer_money = $balanceList[$business_type]['shop_transfer_money'] ?? 0; // 获取店转金额

        return ['money'=>$money,'complimentary_money'=>$complimentary_money,'shop_transfer_money'=>$shop_transfer_money];
    }

	public function swipeCustomerData(){
	    //客户分类 73是A类 72是B类 71是C类 70是D类
	    $customer_type = 73;
	    $data = self::with(['shopRefundOrder' => function($query){
	            $query->field('id,uid,deal_time,type,refund_type,is_pay,status,pay_amount');
	            $query->where('type',3);
	            $query->where('refund_type','<>','101.03');
	            $query->where('is_pay',1);
	            $query->where('status',2);
	            $query->where('pay_amount','>=',500);
	            $query->order('deal_time');
	            //$query->limit(2);
	        }])->where('cj_money',0)->where('member_classification',$customer_type)->field('id,customer_name')->limit(10000000)->select()->toArray();
	        echo count($data);die;
	        foreach($data as $key=>$v){
	            if(isset($v['shopRefundOrder'][0])){
	                $update=[];
	                $update['cj_time'] = $v['shopRefundOrder'][0]['dealTime'];
	                $update['cj_money'] = $v['shopRefundOrder'][0]['payAmount'];
	                $update['cj_order_id'] = $v['shopRefundOrder'][0]['id'];

	                self::where('id',$v['id'])->update($update);
	            }
	        }

	}
    //获取客户的消耗金额
//     public function getCustomerAmountConsumed($customerBalance=[]){

//         $money = $customerBalance['money'];  //客户的本金余额

//         $complimentary_money =  $customerBalance['complimentary_money']; //客户的赠金余额

//         $shop_transfer_money = $customerBalance['shop_transfer_money']; //客户的店转余额

// //        var_dump($money,$complimentary_money,$shop_transfer_money);die;

//         $actual_order_amout = $customerBalance ['actual_order_amout'];//订单的金额

//         $pay_dianzhuan_amount = $pay_zengjin_amount = $pay_benjin_amount = 0.00; //消耗的电转、赠金、本金

//         if($complimentary_money == 0 && $shop_transfer_money == 0  ) {
//             $pay_benjin_amount = $actual_order_amout;
//         }else{
//             if ($money == 0){
//                 if($complimentary_money <=0 & $shop_transfer_money >0){    //仅扣店转

//                     if ($shop_transfer_money >= $actual_order_amout) {
//                         $pay_dianzhuan_amount = $actual_order_amout;
//                     }else{
//                         $pay_dianzhuan_amount = $shop_transfer_money;
//                         $pay_benjin_amount = bcsub($actual_order_amout,$shop_transfer_money,2);
//                     }
//                 }else if($complimentary_money >0 && $shop_transfer_money <= 0){  //仅扣赠金

//                     if ($complimentary_money >= $actual_order_amout) {
//                         $pay_zengjin_amount = $actual_order_amout;
//                     }else{
//                         $pay_zengjin_amount = $complimentary_money;
//                         $pay_benjin_amount = bcsub($actual_order_amout,$complimentary_money,2);
//                     }
//                 }else if($complimentary_money >0 && $shop_transfer_money > 0){
//                     $zeng_dian_add = bcadd($complimentary_money,$shop_transfer_money,2); //赠金余额与店转余额的和
//                     $pay_complimentary_money = round(number_format($complimentary_money/$zeng_dian_add ,2) * $actual_order_amout,2); //需要支付的赠金
//                     $pay_shop_transfer_money = round(number_format($shop_transfer_money/$zeng_dian_add, 2) * $actual_order_amout,2); //需要支付的店转
// //                    var_dump($pay_shop_transfer_money,$pay_complimentary_money);die;
//                     if($shop_transfer_money >= $pay_shop_transfer_money){ //店转够扣
//                         $pay_dianzhuan_amount = $pay_shop_transfer_money;
//                         if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
//                             $pay_zengjin_amount = $pay_complimentary_money;
//                             $pay_benjin_amount = 0;
//                         }else{
//                             //赠金不够
//                             $need_pay_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
//                             $pay_zengjin_amount = $complimentary_money;
//                             $pay_benjin_amount = $need_pay_money_diff;
//                         }
//                     }else{
//                         //店转不够扣
//                         $pay_dianzhuan_amount = $shop_transfer_money;
//                         $need_pay_shop_transfer_money_diff = bcsub($pay_shop_transfer_money,$shop_transfer_money,2);
//                         $pay_complimentary_money = bcadd($need_pay_shop_transfer_money_diff,$pay_complimentary_money,2); //需支付的赠金+（需支付的店转-店转余额）
//                         if($complimentary_money>=$pay_complimentary_money){ //赠金够扣
//                             $pay_zengjin_amount = $pay_complimentary_money;
//                             $pay_benjin_amount = 0;
//                         }else{
//                             $pay_zengjin_amount = $complimentary_money;
//                             $need_pay_complimentary_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
//                             $pay_benjin_amount = bcadd($need_pay_complimentary_money_diff,0,2);
//                         }
//                     }
//                 }
//             }else if($money >0){

//                 if($complimentary_money <=0 & $shop_transfer_money >0){    //仅扣店转

//                     $ben_dian_add = bcadd($money,$shop_transfer_money,2); //本金与店转余额的和
//                     $pay_money = round(number_format($money/$ben_dian_add ,2) * $actual_order_amout,2); //需要支付的本金
//                     $pay_shop_transfer_money = round(number_format($shop_transfer_money/$ben_dian_add, 2) * $actual_order_amout,2); //需要支付的店转

//                     if ($shop_transfer_money >= $pay_shop_transfer_money) { //店转够扣
//                         $pay_dianzhuan_amount = $pay_shop_transfer_money;
//                         $pay_benjin_amount = $pay_money;
//                     }else{ //店转不够扣
//                         $pay_dianzhuan_amount = $shop_transfer_money;
//                         //需要支付的本金+不够扣的店转
//                         $pay_benjin_amount = bcadd($pay_money,bcsub($pay_shop_transfer_money,$shop_transfer_money,2),2);
//                     }

//                 }else if($shop_transfer_money <= 0 && $complimentary_money >0 ){  //仅扣赠金

//                     $ben_zen_add = bcadd($money,$complimentary_money,2); //本金与赠金余额的和
//                     $pay_money = round(number_format($money/$ben_zen_add ,2) * $actual_order_amout,2); //需要支付的本金
//                     $pay_complimentary_money = round(number_format($complimentary_money/$ben_zen_add, 2) * $actual_order_amout,2); //需要支付的赠金
//                     if ($complimentary_money >= $pay_complimentary_money) { //赠金够扣
//                         $pay_zengjin_amount = $pay_complimentary_money;
//                         $pay_benjin_amount = $pay_money;
//                     }else{
//                         $pay_zengjin_amount = $complimentary_money;
//                         //需要支付的本金+不够扣的赠金
//                         $pay_benjin_amount = bcadd($pay_money,bcsub($pay_complimentary_money,$complimentary_money,2),2);
//                     }

//                 }else if($complimentary_money >0 && $shop_transfer_money > 0){

//                     $zeng_dian_add = bcadd($complimentary_money,$shop_transfer_money,2); //赠金和店转的和

//                     $bili_money = round(number_format($money/(bcadd($money,$zeng_dian_add,2)),2),2); //需要支付的本金利率

//                     $pay_money = round($bili_money*$actual_order_amout,2);  //需要支付的本金

//                     $zeng_dian_bili = 1- $bili_money;

//                     $pay_zeng_bili = number_format($complimentary_money/$zeng_dian_add,4)*$zeng_dian_bili; //需要支付的赠金利率

//                     $pay_dian_bili = number_format($shop_transfer_money/$zeng_dian_add,4)*$zeng_dian_bili; //需要支付的赠金利率

//                     $pay_complimentary_money = round($pay_zeng_bili * $actual_order_amout,2); //需要支付的赠金

//                     $pay_shop_transfer_money = round($pay_dian_bili * $actual_order_amout,2);//需要支付的店转


//                     if($shop_transfer_money>=$pay_shop_transfer_money){ //电转够扣
//                         $pay_dianzhuan_amount = $pay_shop_transfer_money;
//                         if($complimentary_money>=$pay_complimentary_money){ //赠金够扣
//                             $pay_zengjin_amount = $pay_complimentary_money;
//                             $pay_benjin_amount = $pay_money;
//                         }else{
//                             //赠金不够
//                             $need_pay_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
//                             $pay_zengjin_amount = $complimentary_money;
//                             $pay_benjin_amount = bcadd($need_pay_money_diff,$pay_money,2);
//                         }
//                     }else{
//                         //电转不够扣
//                         $pay_dianzhuan_amount = $shop_transfer_money;
//                         $need_pay_shop_transfer_money_diff = bcsub($pay_shop_transfer_money,$shop_transfer_money,2);
//                         $pay_complimentary_money = bcadd($need_pay_shop_transfer_money_diff,$pay_complimentary_money,2);
//                         if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
//                             $pay_zengjin_amount = $pay_complimentary_money;
//                             $pay_benjin_amount = $pay_money;
//                         }else{
//                             $pay_zengjin_amount = $complimentary_money;
//                             $need_pay_complimentary_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
//                             $pay_benjin_amount = bcadd($need_pay_complimentary_money_diff,$pay_money,2);
//                         }
//                     }
//                 }else{
//                     // 扣本金
//                     $pay_zengjin_amount = 0;
//                     $pay_dianzhuan_amount = 0;
//                     $pay_benjin_amount = $actual_order_amout;
//                 }
//             }
//         }

//         return ['pay_dianzhuan_amount'=>$pay_dianzhuan_amount,'pay_zengjin_amount'=>$pay_zengjin_amount,'pay_benjin_amount'=>$pay_benjin_amount];
//     }

    public function getCustomerAmountConsumed($customerBalance=[]){

        $money = $customerBalance['money'];  //客户的本金余额

        $complimentary_money =  $customerBalance['complimentary_money']; //客户的赠金余额

        $shop_transfer_money = $customerBalance['shop_transfer_money']; //客户的店转余额


        $actual_order_amout = $customerBalance ['actual_order_amout'];//订单的金额

        $pay_dianzhuan_amount = $pay_zengjin_amount = $pay_benjin_amount = 0.00; //消耗的电转、赠金、本金

        if($complimentary_money == 0 && $shop_transfer_money == 0  ) {
            $pay_benjin_amount = $actual_order_amout;
        }else{
            if ($money == 0){
                if($complimentary_money <=0 & $shop_transfer_money >0){    //仅扣店转

                    if ($shop_transfer_money >= $actual_order_amout) {
                        $pay_dianzhuan_amount = $actual_order_amout;
                    }else{
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        $pay_benjin_amount = bcsub($actual_order_amout,$shop_transfer_money,2);
                    }
                }else if($complimentary_money >0 && $shop_transfer_money <= 0){  //仅扣赠金

                    if ($complimentary_money >= $actual_order_amout) {
                        $pay_zengjin_amount = $actual_order_amout;
                    }else{
                        $pay_zengjin_amount = $complimentary_money;
                        $pay_benjin_amount = bcsub($actual_order_amout,$complimentary_money,2);
                    }
                }else if($complimentary_money >0 && $shop_transfer_money > 0){
                    $zeng_dian_add = bcadd($complimentary_money,$shop_transfer_money,2); //赠金余额与店转余额的和
                    $pay_complimentary_money = round(number_format($complimentary_money/$zeng_dian_add ,2) * $actual_order_amout,2); //需要支付的赠金
                    $pay_shop_transfer_money = bcsub($actual_order_amout,$pay_complimentary_money,2); //需要支付的店转 = 订单金额-需要支付的赠金

                    if($shop_transfer_money >= $pay_shop_transfer_money){ //店转够扣
                        $pay_dianzhuan_amount = $pay_shop_transfer_money;
                        if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                            $pay_benjin_amount = 0;
                        }else{
                            //赠金不够
                            $need_pay_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_zengjin_amount = $complimentary_money;
                            $pay_benjin_amount = $need_pay_money_diff;
                        }
                    }else{
                        //店转不够扣
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        $need_pay_shop_transfer_money_diff = bcsub($pay_shop_transfer_money,$shop_transfer_money,2);
                        $pay_complimentary_money = bcadd($need_pay_shop_transfer_money_diff,$pay_complimentary_money,2); //需支付的赠金+（需支付的店转-店转余额）
                        if($complimentary_money>=$pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                            $pay_benjin_amount = 0;
                        }else{
                            $pay_zengjin_amount = $complimentary_money;
                            $need_pay_complimentary_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_benjin_amount = bcadd($need_pay_complimentary_money_diff,0,2);
                        }
                    }
                }
            }else if($money >0){

                if($complimentary_money <=0 & $shop_transfer_money >0){    //仅扣店转

                    $ben_dian_add = bcadd($money,$shop_transfer_money,2); //本金与店转余额的和
                    $pay_money = round(number_format($money/$ben_dian_add ,2) * $actual_order_amout,2); //需要支付的本金
                    $pay_shop_transfer_money =  bcsub($actual_order_amout,$pay_money,2); //需要支付的店转 = 订单金额-需要支付的本金

                    if ($shop_transfer_money >= $pay_shop_transfer_money) { //店转够扣
                        $pay_dianzhuan_amount = $pay_shop_transfer_money;
                        $pay_benjin_amount = $pay_money;
                    }else{ //店转不够扣
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        //需要支付的本金+不够扣的店转
                        $pay_benjin_amount = bcadd($pay_money,bcsub($pay_shop_transfer_money,$shop_transfer_money,2),2);
                    }

                }else if($shop_transfer_money <= 0 && $complimentary_money >0 ){  //仅扣赠金

                    $ben_zen_add = bcadd($money,$complimentary_money,2); //本金与赠金余额的和

                    $pay_money = round(number_format($money/$ben_zen_add ,2) * $actual_order_amout,2); //需要支付的本金

                    $pay_complimentary_money =bcsub($actual_order_amout,$pay_money,2); // 需要支付的赠金 = 订单金额-需要支付的本金
                    if ($complimentary_money >= $pay_complimentary_money) { //赠金够扣
                        $pay_zengjin_amount = $pay_complimentary_money;
                        $pay_benjin_amount = $pay_money;
                    }else{
                        $pay_zengjin_amount = $complimentary_money;
                        //需要支付的本金+不够扣的赠金
                        $pay_benjin_amount = bcadd($pay_money,bcsub($pay_complimentary_money,$complimentary_money,2),2);
                    }

                }else if($complimentary_money >0 && $shop_transfer_money > 0){


                    $zeng_dian_add = bcadd($complimentary_money,$shop_transfer_money,2); //用户的余额：赠金和店转的和

                    $bili_money = bcdiv($money,(bcadd($money,$zeng_dian_add,2)),2); //需要支付的本金利率

                    $zeng_dian_bili  = 1 - $bili_money;

                    $pay_money = bcmul($bili_money,$actual_order_amout,2);  //需要支付的本金

                    $zeng_dianMoney  = bcsub($actual_order_amout,$pay_money,2); // 需要支付的赠金+店转

                    $zeng_bili = bcmul(bcdiv($complimentary_money,$zeng_dian_add,2),$zeng_dian_bili,2);//赠金的利率


                    $pay_complimentary_money  = bcmul($complimentary_money,$zeng_bili,2);//需要支付的赠金

                    $pay_shop_transfer_money = bcsub($zeng_dianMoney,$pay_complimentary_money,2);//需要支付的店转


                    if($shop_transfer_money>=$pay_shop_transfer_money){ //电转够扣
                        $pay_dianzhuan_amount = $pay_shop_transfer_money;
                        if($complimentary_money>=$pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                            $pay_benjin_amount = $pay_money;
                        }else{
                            //赠金不够
                            $need_pay_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_zengjin_amount = $complimentary_money;
                            $pay_benjin_amount = bcadd($need_pay_money_diff,$pay_money,2);
                        }
                    }else{
                        //电转不够扣
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        $need_pay_shop_transfer_money_diff = bcsub($pay_shop_transfer_money,$shop_transfer_money,2);
                        $pay_complimentary_money = bcadd($need_pay_shop_transfer_money_diff,$pay_complimentary_money,2);
                        if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                            $pay_benjin_amount = $pay_money;
                        }else{
                            $pay_zengjin_amount = $complimentary_money;
                            $need_pay_complimentary_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_benjin_amount = bcadd($need_pay_complimentary_money_diff,$pay_money,2);
                        }
                    }
                }else{
                    // 扣本金
                    $pay_zengjin_amount = 0;
                    $pay_dianzhuan_amount = 0;
                    $pay_benjin_amount = $actual_order_amout;
                }
            }else{
                //本金为负
                if($complimentary_money>0 && $shop_transfer_money<=0 ){
                    //仅扣赠金
                    if ($complimentary_money >= $actual_order_amout) {
                        $pay_zengjin_amount = $actual_order_amout;
                    }else{
                        $pay_zengjin_amount = $complimentary_money;
                        $pay_benjin_amount = bcsub($actual_order_amout,$complimentary_money,2);
                    }

                }else if($complimentary_money<=0 && $shop_transfer_money>0){
                    //仅扣店转
                    if ($shop_transfer_money >= $actual_order_amout) {
                        $pay_dianzhuan_amount = $actual_order_amout;
                    }else{
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        $pay_benjin_amount = bcsub($actual_order_amout,$shop_transfer_money,2);
                    }
                }else{
                    //赠金电转都有钱 按照比例
                    $zeng_dian_add = bcadd($complimentary_money,$shop_transfer_money,2); //用户的余额：赠金和店转的和

                    $bili_complimentary_money = bcdiv($complimentary_money,$zeng_dian_add,2); //需要支付的赠金利率

                    $pay_complimentary_money = bcmul($actual_order_amout,$bili_complimentary_money,2);  //需要支付的赠金

                    $pay_shop_transfer_money = bcsub($actual_order_amout,$pay_complimentary_money,2);  //需要支付的店转

                    if($shop_transfer_money >= $pay_shop_transfer_money){ //电转够扣
                        $pay_dianzhuan_amount = $pay_shop_transfer_money;
                        if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                        }else{
                            //赠金不够
                            $need_pay_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_zengjin_amount = $complimentary_money;
                            $pay_benjin_amount = bcadd($need_pay_money_diff,0,2);
                        }
                    }else{
                        //电转不够扣
                        $pay_dianzhuan_amount = $shop_transfer_money;
                        $need_pay_shop_transfer_money_diff = bcsub($pay_shop_transfer_money,$shop_transfer_money,2);

                        $pay_complimentary_money = bcadd($need_pay_shop_transfer_money_diff,$pay_complimentary_money,2);

                        if($complimentary_money >= $pay_complimentary_money){ //赠金够扣
                            $pay_zengjin_amount = $pay_complimentary_money;
                            $pay_benjin_amount = 0;
                        }else{
                            $pay_zengjin_amount = $complimentary_money;
                            $need_pay_complimentary_money_diff = bcsub($pay_complimentary_money,$complimentary_money,2);
                            $pay_benjin_amount = bcadd($need_pay_complimentary_money_diff,0,2);
                        }
                    }
                }

            }
        }

        return ['pay_dianzhuan_amount'=>$pay_dianzhuan_amount,'pay_zengjin_amount'=>$pay_zengjin_amount,'pay_benjin_amount'=>$pay_benjin_amount];
    }


    /**
     * 设置客户的年龄
     */
    public function setCustomerAge(): bool
    {
        $field = 'id,birthday';
        // try {
            //处理更新的数据
            $list  = $this -> field($field) -> select() -> toArray();
            $saveAll = array();
            foreach($list as $key => $val){
                if ($val['birthday']) {
                    $setData            = array();
                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']));
                    $setData['id']      = $val['id'];
                    $saveAll[]          = $setData;
                }
            }

            if($saveAll){
                // print_r($setData);exit;
                $res = $this -> saveAll($saveAll);
                if ($res === false) {
                   $this->error = '更新失败';
                   return array();
                }
            }
        // } catch (\Exception $e) {
        //     $this->error = '更新失败2';
        //     return false;
        // }
        return true;
    }

    /**
     * 列表
     * 会员在门诊和门店的消费合并，达到会员条件时，成为会员
     * 拥有数据权限:
     * 1. 门店看自己
     * 2. 后台看列表
     * @param  array $request 请求参数
     * --------------------------------------------------------------------------+
     * 目前存在的搜索条件
     * -+
     * $request                     搜索参数集
     * --+
     * page                      int       页码
     * limit                     int       每页的数据
     * create_time               string    客户录入的日期: ****-**-**
     * customer_name             string    客户的名称
     * sex                       int       性别: 0未知 1男 2女
     * source_id                 int       客户来源
     * effective_entry           int       进店标识: 0未知 1是 2否
     * membership_leve           int       会员等级
     * member_classification     int       客户分类
     * repair_progress           int       修复进展: 0未知 其他设置按照id
     * scar_id                   int       疤痕类型: 关联查询 -- customer_scar表
     * consumption               decimal   消费金额
     * consumption_type          int       搜索消费金额的范围: 1大于 2小于 3等于
     * age                       int       客户的年龄
     * --------------------------------------------------------------------------+
     * @return array
     */
    public function getDataList(array $request): array
    {

        // try {
            // 分页数据


			$paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
			$paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

			//var_dump($request);
			$user_id = $request['user_id'];
            //实例化搜索工具
            $whereLogic  = new WhereLogic();

            //初始化设置搜索的店铺集
            $whereLogic  -> setWhereSearch($request);

            //疤痕明细搜索
            $scarId = $request['scar_id']??0;

			//疤痕类型搜索（2024-06-15 新增）
			$scarTypeId = $request['scar_type_id']??0;






            // $whereType              = array();
            // $whereType['scar_id']   = '=';
            // $whereLogic             -> setWhereType($whereType);
            // $where                  = $whereLogic -> getWhere($request,$whereType);
//            $customerIds            = array();
//            if (isset($request['scar_id'])) {
//                $customerIds        = Db::name('customer_scar')->where('customer_setting_id_type','=',$request['scar_id'])->column('customer_id');
//            }
            //实例化搜索数据集
            // $addSearch                          = array();
            // if ($customerIds) {
            //     $addSearch['id']                = $customerIds;
            //     $whereType['id']                = 'in';
            // }


            // if ($addSearch) {
            //     $whereLogic     -> setWhereSearch($addSearch,1);
            // }

            $whereType                          = array();
            //调试使用
            // $addSearch['id']                    = 4;
            // $whereType['id']                    = '=';
            // $whereLogic         -> setWhereSearch($addSearch,1);
            // print_r(123465);
            // exit;

            // $whereType['create_time']           = '=';
            $whereType['customer_name']         = 'like';
            // $whereType['sex']                   = '=';
            $whereType['source_id']             = '=';
            // $whereType['effective_entry']       = '=';
            $whereType['membership_leve']       = '=';
            $whereType['member_classification'] = '=';
            $whereType['repair_progress']       = '=';
            // $whereType['consumption']           = '=';
            // $whereType['consumption_type']      = '=';
            $whereType['age']                   = '=';
            $whereType['telephone']             = '=';
            $whereLogic  -> setWhereType($whereType);
            $where       = $whereLogic -> getWhere($request,$whereType);
            if (isset($request['create_time']) && !empty($request['create_time'])) {
                // code...
                array_push($where,['create_time','>=',strtotime($request['create_time'].' 00:00:00')]);
                array_push($where,['create_time','<=',strtotime($request['create_time'].' 23:59:59')]);
            }

//            if (!empty($customerIds)) {
//                array_push($where,['id','in',$customerIds]);
//            }

            if (isset($request['shop_id'])&&intval($request['shop_id'])>0) {
                // code...
                array_push($where,['shop_id','=',$request['shop_id']]);
            }

            if (isset($request['nurse_id'])&&intval($request['nurse_id'])>0) {
                // code...
                array_push($where,['nurse_id','=',$request['nurse_id']]);
            }
            // if (!empty($request['consumption'])){
            //     if (!empty($request['consumption_type'])){
            //         if ($request['consumption']==1){
            //             $consumption_type = '>=';
            //         }else if($request['consumption']==2){
            //             $consumption_type = '<=';
            //         }else{
            //             $consumption_type = '=';
            //         }
            //         array_push($where,['consumption',$consumption_type,$request['consumption_type']]);
            //     }
            // }
			//查询该员工的 查询权限和客户档案
			$userList = Db::name('admin_user')->alias('u')
								->join('shop_person s', 'u.shop_person_id=s.id', 'LEFT')
			                    ->where('u.id','=',$user_id)
			                    ->where('u.is_status','=',0)
			                    ->column('u.type,u.structure_name,u.structure_id,u.shop_person_id,s.position_id');
			/* //判断客服 归属的 只能查看自己的客户档案
			if($userList[0]['type'] ==1  && $userList[0]['structure_id'] =='8' ){
				array_push($where,['operator','=',$user_id]);
			} */
			//判断店面护理师 只能查看自己名下的 客户档案
			if($userList[0]['type'] ==3  && $userList[0]['position_id'] =='9' ){
				array_push($where,['nurse_id','=',$userList[0]['shop_person_id']]);
			}


            $consumption_min = '';
            if(isset($request['consumption_min']) && is_numeric($request['consumption_min'])){
                $consumption_min = $request['consumption_min'];
            }
            if ($consumption_min !== ''){
                array_push($where,['consumption','>=',$consumption_min]);
            }
            $consumption_max = '';
            if(isset($request['consumption_max']) && is_numeric($request['consumption_max'])){
                $consumption_max = $request['consumption_max'];
            }
            if ($consumption_max !== ''){
                array_push($where,['consumption','<=',$consumption_max]);
            }
            $shopIds = $request['shopIds'] ?? array();
            // array_push($where,['shop_id','in',$shopIds]);
// print_r($where);
            // 年龄搜索
            $sexmin = $request['agemin'] ?? '';
            if ($sexmin !== ''){
                array_push($where,['age','>=',$sexmin]);
            }
            $sexmax = $request['agemax'] ?? '';
            if ($sexmax !== ''){
                array_push($where,['age','<=',$sexmax]);
            }
            $sex = $request['sex'] ?? 0;
            if (!empty($sex)){
                array_push($where,['sex','=',$sex]);
            }
            // 下述列表基础数据获取 //
            $isDrain    = $request['isDrain'] ?? 0;
            $isNewOrder = $request['isNewOrder'] ?? 0;
            $isWarning  = $request['isWarning'] ?? 0;
            // 新单数据获取 //
            if ($isNewOrder){
                // $newOrderWhere = [];
                // $endThismonth = time();
                // $beginThismonth = bcsub($endThismonth,2592000);
                // array_push($newOrderWhere,['deal_time','>=',$beginThismonth]);
                // array_push($newOrderWhere,['deal_time','<=',$endThismonth]);
                // array_push($newOrderWhere,['order_type','=',1]);
                // array_push($newOrderWhere,['pay_amount','>=',500]);
                // array_push($newOrderWhere,['type','=',3]);
                // if($shopIds){
                //     array_push($newOrderWhere,['shop_id','in',$shopIds]);
                // }
                // $newOrderCustomerIds = Db::name("shop_refund_order") -> where($newOrderWhere) -> group('uid') -> column('uid');
                // if ($newOrderCustomerIds) {
                //     $newOrderCustomerIds = array_values(array_unique($newOrderCustomerIds));
                //     array_push($where,['id','in',$newOrderCustomerIds]);
                // }
				//根据客保部进行功能调整关闭--2022.04.19
				//2023-02-14 关闭 成交时间搜索
                array_push($where,['cj_time','>',0]); //
				array_push($where,['cj_money','>=',500]); //
				array_push($where,['final_consumption|final_service','>','0']); //非活跃顾客 --之前老顾客
            }
            // 预警数据获取 //
            // 流失数据获取 //
            $export = $request['export'] ?? 0;

            if ($export == 1){
                $ids = $request['id'] ?? [];
                array_push($where,['id','in',$ids]);
            }

            $huiyuan_status = $request['huiyuan_status'] ?? 0;

            $huiyuan_chadianguoqi_time = 24*60*60*30;

            if ($huiyuan_status==1) {
                array_push($where,['be_overdue_time','<',time()]);
            }else if($huiyuan_status==2){
                array_push($where,['be_overdue_time','>',time()]);
            }else if($huiyuan_status==3){
                array_push($where,['be_overdue_time','<=',time()+$huiyuan_chadianguoqi_time]);
                array_push($where,['be_overdue_time','>',time()]);
            }
            //客户标签
            $member_label = $request['member_label'] ?? 0;
            if ($member_label>0) {
                array_push($where,['member_label','like','%'.$member_label.'%']);
            }
            //成交时间
            $cj_time = $request['cj_time'] ?? '';
            if ($cj_time) {
                array_push($where,['cj_time','>=',strtotime(date('Y-m-d',strtotime($cj_time)).'00:00:00')]);
                //array_push($where,['cj_time','<=',strtotime(date('Y-m-d',strtotime($cj_time)).'23:59:59')]);
            }

			$cj_endtime = $request['cj_endtime'] ?? '';
			if ($cj_endtime) {

			    array_push($where,['cj_time','<=',strtotime(date('Y-m-d',strtotime($cj_endtime)).'23:59:59')]);

			}

			//var_dump($where);

            $is_join_shop = $request['is_join_shop'] ?? 0;
            if ($is_join_shop == 1){
                array_push($where,['first_time','>',0]);
            }else if($is_join_shop == 2){
                array_push($where,['membership_leve','>',0]);
            }else if($is_join_shop == 3 || $is_join_shop == 4){//流失-yujing
                $bei = $is_join_shop == 3?4:1;
                if($is_join_shop == 3){
                    array_push($where,['month4','=',4]);
                }else{
                    array_push($where,['month1','=',1]);
                }
                $jzxzTime=strtotime("2022-01-01");
                array_push($where,['cj_time','>',$jzxzTime]);

                array_push($where,['cj_time','>',$jzxzTime]);

                $shopIdmz=[73782775131388,73782774881835,73782775392774,73782775377728,73782775206631,73782775085647,73782774991693];

                array_push($where,['shop_id','not in',$shopIdmz]);
                //$where[] = ['user.id', 'not in', $unUserId];

                // array_push($where,['monthly_care','=',$bei]);
                // array_push($where,['monthly_consumption','=',$bei]);
                // array_push($where,['monthly_case','=',$bei]);
                // array_push($where,['history_graduation','=',$bei]);
            }

            // $this->where('final_consumption','=',null)->update(['graduation'=>0]);

            $shopWhere = [];

            //array_push($shopWhere,['status','=',1]);
            //array_push($shopWhere,['shop_id','not in','73998717474810,73782774792133']);

            $type = $request['type'] ?? [];


            if($type){
                array_push($shopWhere,['type','=',$type]);
            }

            $shopIds = $request['shopIds'] ?? [];


            if($shopIds){
                array_push($shopWhere,['shop_id','in',$shopIds]);
            }

            $marketId = $request['market_id'] ?? "";

            // echo "<pre>";
            // print_r($request);
            // die();

            if($marketId){
                array_push($shopWhere,['market_id','=',$marketId]);
            }

            $shopList = Db::name('shop')->where($shopWhere)->column('shop_id');

            if (!empty($shopList)) {
                array_push($where,['shop_id','in',$shopList]);
            }

            $turn_status = $request['turn_status'] ?? 0;
            if($turn_status == 1){
                array_push($where,['turn_status','=',1]);
            }
            $first_time_start = $request['first_time_start'] ?? '';
            // $first_time_start = empty($request['first_time_start']) ? 0 : strtotime($request['first_time_start']);
            // if($first_time_start > 0){
            //     array_push($where,['first_time','>=',$first_time_start]);
            // }
            $first_time_end = $request['first_time_end'] ?? '';
            // $first_time_end = empty($request['first_time_end']) ? 0 : strtotime($request['first_time_end']);
            // if($first_time_end > 0){
            //     array_push($where,['first_time','<=',$first_time_end]);
            // }
            $create_time_start = $request['create_time_start'] ?? '';
            $create_time_start = empty($request['create_time_start']) ? 0 : strtotime($request['create_time_start']);
            if($create_time_start > 0){
                array_push($where,['create_time','>=',$create_time_start]);
            }
            $create_time_end = $request['create_time_end'] ?? '';
            $create_time_end = empty($request['create_time_end']) ? 0 : strtotime($request['create_time_end']);
            if($create_time_end > 0){
                array_push($where,['create_time','<=',$create_time_end]);
                // print_r($where);exit;
            }
            //last_kftime
            $last_kftime_start = $request['last_kftime_start'] ?? '';
            $last_kftime_start = empty($request['last_kftime_start']) ? 0 : strtotime($request['last_kftime_start']);
            if($last_kftime_start > 0){
                array_push($where,['last_kftime','>=',$last_kftime_start]);
            }
            $last_kftime_end = $request['last_kftime_end'] ?? '';
            $last_kftime_end = empty($request['last_kftime_end']) ? 0 : strtotime($request['last_kftime_end']);
            if($last_kftime_end > 0){
                array_push($where,['last_kftime','<=',$last_kftime_end]);
            }
            $customer_service_name = $request['customer_service_name'] ?? 0;
            if(!empty($customer_service_name)){
                $ids =  Db::name('admin_user')->where('realname','like','%'.$customer_service_name.'%')->column('id');
                array_push($where,['operator','in',$ids]);
            }
            $difficulty_level = $request['difficulty_level'] ?? 0;
            if($difficulty_level){
                array_push($where,['difficulty_level','=',$difficulty_level]);
            }
            $effective_entry = $request['effective_entry'] ?? 0;
            if($effective_entry == 1){
                array_push($where,['first_time','>',0]);
            }else if($effective_entry == 2){
                array_push($where,['first_time','=',0]);
            }
            $where2 = $where;
            //print_r($where);
            $customer_name_phone = $request['customer_name_phone'] ?? '';
            $dataCounts   = $this->where($where)
                            ->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                if(!empty($customer_name_phone)){
                                    $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                    $query->whereOr('telephone', '=', $customer_name_phone);
                                }
                            })
                            ->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                });
                            if(!empty($scarId))
                            {
                                $dataCounts = $dataCounts->where('id', 'IN', function ($query)use($scarId) {
                                    $query->table('xy_customer_scar')->where('customer_setting_id_type','=',$scarId)->field('customer_id');
                                });
                            }

							if(in_array($scarTypeId,[1,2,3])){
							    $list = $dataCounts->where('id', 'IN', function ($query)use($scarTypeId) {
									switch ($scarTypeId){
										case 1:
											$query->table('xy_customer_scar')->whereIn('customer_setting_id_type',[1,2,3,4,5,6,7,8,655,656])->field('customer_id');
											break;
										case 2:
											$query->table('xy_customer_scar')->where('customer_setting_id_type',10)->field('customer_id');
											break;
										case 3:
											$query->table('xy_customer_scar')->whereIn('customer_setting_id_type',[9,11,12])->field('customer_id');
											break;
									}
								});
							}

                            $dataCounts = $dataCounts->count();


                            $aaauser_id = $request['user_id'];
                            // if($aaauser_id == 109){
                            // //   print_r($this->getLastSql());exit;
                            // }
                            // print_r($where);exit;
                           // print_r($this->getLastSql());exit;
                            //print_r($this->getLastSql());exit;
                            // print_r(1);exit;
            if ($dataCounts) {

                $field          = ['id', 'customer_name', 'sex','telephone', 'birthday', 'effective_entry', 'shop_id','source_id','effective_entry','status','create_time','first_time','second_time','member_classification','turn_status','age','membership_leve','nurse_id','repair_progress','consumption','new_join_shop_time','final_consumption','final_service','join_time','be_overdue_time','cj_time','cj_money','operator','last_kftime','difficulty_level,introducer,source_type_id'];
                if ($is_join_shop == 1) {
                    // code...
                    $orderby    = 'new_join_shop_time DESC';
                } else if($is_join_shop == 2){
                    $orderby    = 'join_time DESC';
                }else{
					$orderby    = 'id DESC';
				}
                if($is_join_shop == 1){
                    $orderby    = 'first_time DESC';
                }
				if($is_join_shop == 7){
				    $orderby    = 'cj_time DESC';
				}
                //print_r($where);exit;
                $list           = $this->where($where)
                                    ->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                    if(!empty($customer_name_phone)){
                                        $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                        $query->whereOr('telephone', '=', $customer_name_phone);
                                    }
                                })
                                ->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                });
                if(!empty($scarId))
                {
                    $list = $list->where('id', 'IN', function ($query)use($scarId) {
                        $query->table('xy_customer_scar')->where('customer_setting_id_type','=',$scarId)->field('customer_id');
                    });
                }

				if(in_array($scarTypeId,[1,2,3])){
				    $list = $list->where('id', 'IN', function ($query)use($scarTypeId) {
						switch ($scarTypeId){
							case 1:
								$query->table('xy_customer_scar')->whereIn('customer_setting_id_type',[1,2,3,4,5,6,7,8,655,656])->field('customer_id');
								break;
							case 2:
								$query->table('xy_customer_scar')->where('customer_setting_id_type',10)->field('customer_id');
								break;
							case 3:
								$query->table('xy_customer_scar')->whereIn('customer_setting_id_type',[9,11,12])->field('customer_id');
								break;
						}
					});
				}

                $list = $list->field($field)->order($orderby)
                    ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                    ->select()->toArray();
                $shopId         = array_values(array_unique(array_column($list, 'shop_id')));
                $nurseId        = array_values(array_unique(array_column($list, 'nurse_id')));
                $operatorIds       = array_values(array_unique(array_column($list, 'operator')));
                $introducerId = array_values(array_unique(array_column($list, 'introducer')));
                $telephone = array_values(array_unique(array_column($list, 'telephone')));
                //获取店铺数据
                $shopList       = Db::name('shop')->where('shop_id', 'in', $shopId)->column('shop_name,market_name', 'shop_id');
                //获取员工数据
                $personList     = Db::name('shop_person')->where('id', 'in', $nurseId)->column('name', 'id');
                //获取会员等级
                $gradeList      = Db::name('customer_grade')->column('name', 'id');
                $adminList      = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');
                //转介绍人
                $shopPerson     = Db::name('shop_person')->where('id', 'in', $introducerId)->column('name', 'id');
                //总金额
                $sumMoney       = Db::name('customer')->where('telephone','in',$telephone)->where('status','=',1)->group('telephone')->column('sum(consumption)', 'telephone');
                //基础配置
                $settingList    = Db::name('setting')->column('name', 'id');
                $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];
                $EntryArr       = ['1' => '是', '2' => '否'];
                //疤痕初始化搜索
                foreach($list as $key => $val){
                    if ($val['birthday']) {
                        $setData            = array();
                        $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']));
                        $setData['id']      = $val['id'];
                        $saveAll[]          = $setData;
                        $list[$key]['age']  = $setData['age'];
                    }
                }

                // if($saveAll){
                //     // print_r($setData);exit;
                //     $res = $this -> saveAll($saveAll);
                // }
                foreach ($list as $key => $val) {
                    $list[$key]['sex']             = $sexArr[$val['sex']] ?? '未知';
                    $list[$key]['effective_entry'] = $EntryArr[$val['effective_entry']] ?? '否';
                    $list[$key]['shop_name']       = $shopList[$val['shop_id']]['shop_name'] ?? '';
                    $list[$key]['market_name']       = $shopList[$val['shop_id']]['market_name'] ?? '';
                    $list[$key]['birthday']        = $val['birthday'] ? date('Y-m-d', $val['birthday']) : '';
                    $list[$key]['source_name']     = $settingList[$val['source_id']] ?? '';
                    $list[$key]['customer_source_name'] = $settingList[$val['source_type_id']] ?? '';
                    // 进店-进店时间-进店状态1未进店2已进店
                    $list[$key]['first_time']      = $val['first_time']?date('Y-m-d H:i',$val['first_time']):'';
                    $list[$key]['new_join_shop_time']      = $list[$key]['first_time']; // 首次进店时间

                    $list[$key]['second_time']      = $val['second_time']?date('Y-m-d H:i',$val['second_time']):'';
                    $list[$key]['second_join_shop_time']      = $list[$key]['second_time']; // 二次进店时间

                    $list[$key]['final_consumption'] = $val['final_consumption'] ? date('Y-m-d H:i',$val['final_consumption']) : '';
                    $list[$key]['final_service'] = $val['final_service'] ? date('Y-m-d H:i',$val['final_service']) : '';
                    $list[$key]['last_kftime'] = $val['last_kftime'] ? date('Y-m-d H:i',$val['last_kftime']) : '';
                    $list[$key]['join_time']   = $val['join_time'] ? date('Y-m-d H:i:s', $val['join_time']) : '';
					if ($val['be_overdue_time'] > 0){
                        if($val['be_overdue_time'] >time()){
                            $list[$key]['huiyuan_status'] = '生效中';
                            if(($val['be_overdue_time']-$huiyuan_chadianguoqi_time) <=time()){
                                $list[$key]['huiyuan_status'] = '即将过期';

                            }
                        }else{
                            $list[$key]['huiyuan_status'] = '已过期';
                        }
                    }else{
                        $list[$key]['huiyuan_status'] = '非会员';
                    }
                    $list[$key]['be_overdue_time'] = $val['be_overdue_time'] ? date('Y-m-d H:i',$val['be_overdue_time']) : '';
                    $list[$key]['first_status']    = $val['first_time'] ? '1' : '2' ;
                    // 会员分类-分类id-分类名称
                    $list[$key]['class_name']      = $settingList[$val['member_classification']] ?? '';
                    // 会员等级
                    $list[$key]['grade_name']      = $gradeList[$val['membership_leve']] ?? '';
                    // 负责人名称
                    $list[$key]['nurse_name']      = $personList[$val['nurse_id']] ?? '';
                    // 转介绍人
                    $list[$key]['introducer']      = $shopPerson[$val['introducer']] ?? '';
                    // 修复进展
                    $list[$key]['progress_name']   = $settingList[$val['repair_progress']] ?? '';
                    //门店+门诊
                    $list[$key]['sum_money']   = $sumMoney[$val['telephone']] ?? 0.00;
                    // 客户疤痕内容
                    // $whereLogic  -> setWhereType($whereType);
                    // $where       = $whereLogic -> getWhere($request,$whereType);
                    //$dataCount   = $this->where($where)->count();
                    $scarList    = Db::name('customer_scar')
                                 ->where('customer_id','=',$val['id'])
                                 ->group('customer_setting_id_type')
                                 ->select()->toArray();
                    $scar_aggregate          = '';
                    if ($scarList){
                        $typeIdArr           = array_column($scarList, 'customer_setting_id_type');
                        foreach ($typeIdArr as $typeK => $typeV){
                            $str = $settingList[$typeV] ?? '';
                            $scar_aggregate .= $str.',';
                        }
                    }
                    $list[$key]['scar_aggregate']        = $scar_aggregate;
                    // 客户的名称
                    $list[$key]['customer_service_name'] = $adminList[$val['operator']] ?? '';
                    // 成交时间
                    $list[$key]['cj_time'] = $val['cj_time'] ? date('Y-m-d H:i:s',$val['cj_time']) : '' ;
                    $list[$key]['cj_money'] = $val['cj_money'];
                    $list[$key]['customer_name_phone'] = $val['customer_name'].'/'.$val['telephone'];
                }
            }

        // } catch (\Exception $e) {
        // }

        /**总数统计**/
        if($dataCounts > 0){
            $cjNum = $this->where($where2)->where('member_classification','=',73)->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                if(!empty($customer_name_phone)){
                                    $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                    $query->whereOr('telephone', '=', $customer_name_phone);
                                }
                            })->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                })->count() ?? 0;
            $yzNum = $this->where($where2)->where('member_classification','=',72)->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                if(!empty($customer_name_phone)){
                                    $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                    $query->whereOr('telephone', '=', $customer_name_phone);
                                }
                            })->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                })->count() ?? 0;
            $ptNum = $this->where($where2)->where('member_classification','=',71)->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                if(!empty($customer_name_phone)){
                                    $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                    $query->whereOr('telephone', '=', $customer_name_phone);
                                }
                            })->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                })->count() ?? 0;
            $zcNum = $this->where($where2)->where('member_classification','=',70)->where(function ($query) use ($customer_name_phone) {
                                // print_r($customer_name_phone);exit;
                                if(!empty($customer_name_phone)){
                                    $query->where('customer_name', 'like', '%'.$customer_name_phone.'%');
                                    $query->whereOr('telephone', '=', $customer_name_phone);
                                }
                            })->where(function ($query) use ($first_time_start,$first_time_end) {
                                // print_r($customer_name_phone);exit;
                                    $firwhere = [];
                                    $twowhere = [];
                                    $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);
                                    if($first_time_start > 0){
                                        array_push($firwhere,['first_time','>=',$first_time_start]);
                                        array_push($twowhere,['second_time','>=',$first_time_start]);
                                    }
                                    $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);
                                    if($first_time_end > 0){
                                        array_push($firwhere,['first_time','<=',$first_time_end]);
                                        array_push($twowhere,['second_time','<=',$first_time_end]);
                                    }
                                    if(!empty($firwhere)){
                                        $query->where(function ($query) use ($firwhere){
                                            $query->where($firwhere);
                                        });
                                        $query->whereOr(function ($query) use ($twowhere){
                                            $query->where($twowhere);
                                        });
                                    }
                                })->count() ?? 0;
            $statisticsData = [
                    'allnum'=>$dataCounts,
                    'cj'=>[
                            'num'=>$cjNum,
                            'zhanbi'=>bcmul(bcdiv($cjNum,$dataCounts,2),100,2).'%'
                        ],
                    'yz'=>[
                            'num'=>$yzNum,
                            'zhanbi'=>bcmul(bcdiv($yzNum,$dataCounts,2),100,2).'%'
                        ],
                    'pt'=>[
                            'num'=>$ptNum,
                            'zhanbi'=>bcmul(bcdiv($ptNum,$dataCounts,2),100,2).'%'
                        ],
                    'zc'=>[
                            'num'=>$zcNum,
                            'zhanbi'=>bcmul(bcdiv($zcNum,$dataCounts,2),100,2).'%'
                        ],
                ];
        }else{
            $statisticsData = [
                'allnum'=>0,
                'cj'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'yz'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'pt'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
                'zc'=>[
                        'num'=>0,
                        'zhanbi'=>'0%'
                    ],
            ];
        }

        /**总数统计**/
		$data              = [];
        $data['list']      = $list ?? [];
        $data['statisticsData'] = $statisticsData;
        $data['dataCount'] = $dataCounts ?? 0;
        // $data['user_id'] = $request['user_id'] ?? 0;
        return $data;
    }


/* 详情
* @param  array $request 请求参数
* @return array
*/
    public function getDataInfo(array $request): array
    {

        $id = $request['id'] ?? 0;
        if (!$id) {
            $this->error = '参数错误';
            return [];
        }
        $info = $this->where('id', '=', $id)->find();
        if (!$info) {
            $this->error = '客户信息不存在';
            return [];
        }
        $info = $info->toArray();
        if($info['turn_customerid']!=0){
            $turnInfo = Db::name('customer')->where('id','=',$info['turn_customerid'])->column('id,shop_id,customer_name,telephone');
            $info['turnName'] = $turnInfo[0]['customer_name'];
            $info['turnPhone']= $turnInfo[0]['telephone'];
        }else{
            $info['turnName']= '';
            $info['turnPhone'] = '';
        }

        // // 添加青春痘 护肤品账户
        // $account = Db::name('customer_balance')->where('customer_id','=',$id)->select()->toArray();

        // if(count($account) <= 2){
        //     // 存储客户的余额信息
        //     $customer_balanceAll = [
        //         [
        //             'shop_id'       => $info['shop_id'],
        //             'customer_id'   => $info['id'],
        //             'balance_category_id'   => 3,
        //         ],[
        //             'shop_id'       => $info['shop_id'],
        //             'customer_id'   => $info['id'],
        //             'balance_category_id'   => 4,
        //         ]
        //     ];

        //     Db::name('customer_balance')->insertAll($customer_balanceAll);

        // }




        $info['birthday']        = $info['birthday'] ? date('Y-m-d', $info['birthday']) : '';
        $info['first_time']      = $info['first_time'] ? date('Y-m-d H:i:s', $info['first_time']) : '';
        $info['second_time']     = $info['second_time'] ? date('Y-m-d H:i:s', $info['second_time']) : '';
        $info['join_time']       = $info['join_time'] ? date('Y-m-d H:i:s', $info['join_time']) : '';
        $info['last_entry_time'] = $info['last_entry_time'] ? date('Y-m-d H:i:s', $info['last_entry_time']) : '';
        $shopField = ['shop_name'];
        $shopInfo  = Db::name('shop')->field($shopField)->where('shop_id', '=', $info['shop_id'])->find();
        $info['shop_name'] = $shopInfo['shop_name'] ?? '';
        $tagInfo = Db::name('customer_tag')->where('customer_id', '=', $info['id'])->column('tag_name');
        $info['tag'] = implode(',',$tagInfo);
        $creatorName = $info['creator_id'] ? Db::name('admin_user')->where('id', '=', $info['creator_id'])->value('realname') : '';
        $info['creator_name'] = $creatorName ?: '';
        $sourceName = $info['source_id'] ? Db::name('customer_source')->where('id', '=', $info['source_id'])->value('name') : '';
        $info['source_name'] = $sourceName ?: '';
        $introducerName = $info['introducer'] ? Db::name('shop_person')->where('id', '=', $info['introducer'])->value('name') : '';
        $info['introducer_name'] = $introducerName ?: '';
        if ($info['province'] || $info['city'] || $info['region']) {
            $areaIdArr = [
                $info['province'] ?: 0,
                $info['city'] ?: 0,
                $info['region'] ?: 0
            ];
            $areaWhere = [
                ['id', 'in', array_unique($areaIdArr)]
            ];
            $areaList = Db::name('area')->where($areaWhere)->column('name', 'id');
        }
        $info['province_name'] = $areaList[$info['province']] ?? '';
        $info['city_name']     = $areaList[$info['city']] ?? '';
        $info['region_name']   = $areaList[$info['region']] ?? '';
        $settingList = Db::name('setting')->column('name', 'id');
        // 处理会员标签
        $member_label_name = '';
        if (empty($info['member_label'])) {
            $member_label = array();
            unset($info['member_label']);
            // $info['member_label_name'] = [];
            $info['member_label'] = [];
            $info['member_label_name'] = $member_label_name;
        }else{
            $member_label = $info['member_label'];
            unset($info['member_label']);
            $member_label_array = explode(',',$member_label);
            $settingList2 = Db::name('setting')->where('category_id','=',7)->column(['name','pid','id'], 'id');
            $mla = [];
            foreach ($member_label_array as $key => $val){
                if ($val == $settingList2[$val]['id']) {
                    $mla[$settingList2[$val]['pid']][] = $val;
                }
            }
            $mal2 = [];
            foreach ($mla as $key => $val){
                $one = '';
                if (isset($settingList[$key])){
                    $one = $settingList[$key].':';
                }
                array_unshift($mla[$key],"".$key);
                foreach ($val as $k => $v) {
                    if (!empty($one)){
                        if($k == 0){
                            if($settingList[$v]){
                                $one = $one.$settingList[$v];
                            }
                        }else{
                            if($settingList[$v]){
                                $one = $one.'/'.$settingList[$v];
                            }
                        }
                    }
                    $mal2[] = [intval($key), intval($v)];
                }
                $member_label_name = empty($member_label_name) ? $one : $member_label_name.'、'.$one;
            }
            // print_r($member_label_name);exit;
            $info['member_label_name'] = $member_label_name;
            // $new = [];
            // foreach ($member_label_array as $key => $val) {
            //     $one = [];
            //     $one['id'] = $val;
            //     $one['name'] = $settingList[$val];
            //     array_push($new,$one);
            //     $info['member_label'][] = intval($val);
            // }
            // print_r($mla);exit;
            // $info['member_label_name'] = $new;
            // $info['member_label'] = array_values($mla);
            $info['member_label'] = $mal2;
            if(!empty($request['is_wx']))
            {
                $info['member_label'] = explode(',',$member_label);
                foreach ($info['member_label'] as $key =>$value)
                {
                    $info['member_label'][$key] = intval($value);
                }
            }
        }

//        疤痕位置类型
        $scarList = Db::name('customer_scar')->where('customer_id', '=', $id)->select()->toArray();
        $gradeList = Db::name('customer_grade')->column(['name'],'id');
        $scarName = [];
        $setScart = array();
        if ($scarList) {
            // $typeIdArr     = array_column($scarList, 'customer_setting_id_type');
            // $positionIdArr = array_column($scarList, 'customer_setting_id_position');
            // $settingIdArr  = array_unique(array_merge($typeIdArr, $positionIdArr));
            // $settingWhere  = [
            //     ['id', 'in', $settingIdArr]
            // ];
            foreach ($scarList as $key => $val) {
                $setScart[$key]['type_id'] = $val['customer_setting_id_type'];
                $setScart[$key]['position_id'] = $val['customer_setting_id_position'];
                $typeName     = $settingList[$val['customer_setting_id_type']] ?? '未知';
                $positionName = $settingList[$val['customer_setting_id_position']] ?? '未知';
                $scarName[] = $typeName . '：' . $positionName;
            }
            // print_r($setScart);exit;
        }
        $info['type_position'] = $scarName;
        $info['scar_type_position'] = array_values($setScart);
        $outreach_id = $info['outreach_id'];

        $shopPersonList = Db::name('shop_person')->where('id','in',[$info['nurse_id'],$outreach_id])->column('name','id') ?? [];
        $nurse_name = $shopPersonList[$info['nurse_id']] ?? '';
        $info['outreach_name'] = $shopPersonList[$info['outreach_id']] ?? 0;
        $info['nurse_name'] = $nurse_name;
        $info['nurse_id']   = $info['nurse_id']?$info['nurse_id']:'';

        //        余额信息
        $balanceField = ['c.name' => 'category_name', 'b.money','b.balance_category_id', 'b.complimentary_money', 'b.shop_transfer_money', 'b.proportion'];
        $balanceList  = Db::name('customer_balance')->alias('b')
            ->join('customer_balance_category c', 'c.id = b.balance_category_id')
            ->where('b.customer_id', '=', $id)->field($balanceField)
            ->select()->toArray();
        // echo '2222';
        // echo "<br/>";



        $balance_category_ids = Db::name('customer_balance_category')->column('id');
        $customer_balance_category_ids = array_values(array_unique(array_column($balanceList,'balance_category_id')));

        $diff_ids = array_diff($balance_category_ids,$customer_balance_category_ids);

        $addData = [];
        foreach ($diff_ids as $key => $value) {
            $one = [];
            $one['shop_id']     = $info['shop_id'];
            $one['customer_id'] = $info['id'];
            $one['balance_category_id'] = $value;
            array_push($addData,$one);
        }


        if($addData){
            Db::name('customer_balance')->insertAll($addData);
            $balanceList  = Db::name('customer_balance')->alias('b')
                ->join('customer_balance_category c', 'c.id = b.balance_category_id')
                ->where('b.customer_id', '=', $id)->field($balanceField)
                ->select()->toArray();
        }



        $money_sum = 0;
        $moneyAll = 0;
        $complimentary_moneyAll = 0;
        $shop_transfer_moneyAll = 0;
        $new = [];

        foreach ($balanceList as $key => $val){
            $moneyAll = bcadd($moneyAll,$val['money'],'2');
            $complimentary_moneyAll = bcadd($val['complimentary_money'],$complimentary_moneyAll,'2');
            $shop_transfer_moneyAll = bcadd($val['shop_transfer_money'],$shop_transfer_moneyAll,'2');
            $money_sum = bcadd($val['complimentary_money'],$val['money'],'2');
            $balanceList[$key]['all_money'] = bcadd($money_sum,$val['shop_transfer_money'],'2');
            // $new[$val['balance_category_id']] = $balanceList[$key];
        }
        // $balanceList = array_values($new);
        $balanceAll = [
            'category_name' => '总计',
            'money' => $moneyAll,
            'complimentary_money' => $complimentary_moneyAll,
            'proportion' => '0/0',
            'shop_transfer_money'=>$shop_transfer_moneyAll,
            'all_money' => bcadd(bcadd($moneyAll,$complimentary_moneyAll,'2'),$shop_transfer_moneyAll,2),
        ];
        array_push($balanceList,$balanceAll);
        $info['blance_list'] = $balanceList ?: [];
        $info['new_join_shop_time'] = $info['new_join_shop_time'] ? date('Y-m-d H:i:s',$info['new_join_shop_time']): '';
        $info['progress_name']   = $settingList[$info['repair_progress']] ?? '';
        $info['class_name']   = $settingList[$info['member_classification']] ?? '';
        $info['source_name']   = $settingList[$info['source_id']] ?? '';
        $info['customer_source_name']   = $settingList[$info['source_type_id']] ?? '';
        $info['membership_leve']   = $gradeList[$info['membership_leve']] ?? '';
        $info['new_order']   = 1;

        $info['consultation_status']="";
        $info['consultation_first_time']="";
        $info['consultation_second_time']="";
        $info['reach_first_time']="";
        $info['reach_second_time']="";
        //额外信息
        $extra = Db::name('customer_extra')->where('customer_id','=',$id)->find();

        if($extra){

            if($extra['consultation_status'] == 1)
            {
                $info['consultation_status']="到院";
            }elseif($extra['consultation_status'] == 2)
            {
                $info['consultation_status']="线上";
            }

            $info['consultation_first_time']   = $extra['consultation_first_time'] ?date('Y-m-d',$extra['consultation_first_time']): '';
            $info['consultation_second_time']   = $extra['consultation_second_time'] ?date('Y-m-d',$extra['consultation_second_time']): '';
            $info['reach_first_time']   = $extra['reach_first_time'] ?date('Y-m-d',$extra['reach_first_time']): '';
            $info['reach_second_time']   = $extra['reach_second_time'] ?date('Y-m-d',$extra['reach_second_time']): '';

        }
        $is_disabled_source = true;

        $user_phone = isset($request['user_phone'])?$request['user_phone']:0;
        if($user_phone>0){
               $position = DB::name('shop_person')->where('phone',$request['user_phone'])->value('position_id');
            if(in_array($position,[7,10])){
                $is_disabled_source = false;
            }else{
                $is_disabled_source = true;
            }
        }

        $setting = DB::name('setting')->whereIn('category_id',[4,15])->field('id,name,category_id')->select()->toArray();
        $yes_update =[665,583,46,47,48,49];
        if(in_array($info['source_id'],$yes_update)){
            $count = DB::name('customer_source_log')->where('customer_id',$info['id'])->count();
            if($count<2) {
                $is_disabled_source = false;
            }
            foreach($setting as $k=>&$v){
                if(!in_array($v['id'],$yes_update)){
                    $v['disabled'] = true;
                }
            }
        }
        // $is_disabled_source =true;
        // $user_id = isset($request['user_id'])?$request['user_id']:0;
        // if($user_id>0){
        //       $position = DB::name('shop_person')->where('id',$request['user_id'])->value('position_id');
        //     if(in_array($position,[7,10])){
        //         $is_disabled_source = false;
        //     }else{
        //         $is_disabled_source = true;
        //     }
        // }

        $info['is_disabled_source'] = $is_disabled_source;

        $is_show_money = true;
        if(!empty($request['user_shop_id'])){
            $is_show_money =false;
        }
        $info['is_show_money'] = $is_show_money;

        $info['setting'] = $setting;
        // unset($info['creator_id'], $info['source_id']);
        // var_dump($info);
        return $info;
    }

    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     */
    public function addData(array $request): bool
    {
        // try {
            $validate = new \app\crm\validate\Customer();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
            if (!isset($request['scar_type_position']) || !isset($request['scar_type_position'][0]['type_id']) || !isset($request['scar_type_position'][0]['position_id'])) {
                $this->error = '请选择疤痕类型和位置';
                return false;
            }
            $bool = true;
            foreach($request['scar_type_position'] as $key => $val) {
                if (!isset($val['type_id']) || !$val['type_id'] || !isset($val['position_id']) || !$val['position_id']) {
                    $bool = false;
                    break;
                }
            }
            if (!$bool) {
                $this->error = '请选择疤痕类型和位置';
                return false;
            }
            $first_time = isset($request['first_time']) ? strtotime($request['first_time']) : '';
            $second_time = isset($request['second_time']) ? strtotime($request['second_time']) : '';
            if(empty($first_time) && empty($second_time)){
                $effective_entry = 0;
            }else if(empty($first_time) && !empty($second_time)){
                $this->error = '二次进店时间不为空，请录入首次进店时间';
                return false;
            }else if(!empty($first_time) && empty($second_time)){
                $effective_entry = 1;
            }else if(!empty($first_time) && !empty($second_time) && $second_time<$first_time){
                $this->error = '首次进店时间不能大于二次进店时间';
                return false;
            }else{
                $effective_entry = 1;
            }
            $age = '';
            if (isset($request['birthday'])) {

               if(empty($request['birthday'])){
				  $age     = '';
			   }else{
				   $age     = bcsub(date('Y'),date('Y',strtotime($request['birthday'])));
			   }
            }
			if(empty($request['turn_customerid'])){
				$turn_customerid = '';
			}else{
				$turnInfoY = Db::name("customer")->where('telephone','=',$request['turn_customerid'])->column('id,shop_id');
				$turn_customerid = $turnInfoY[0]['id'];
			}

            $shopId = intval($request['shop_id']);
            $data = [
                'shop_id'               => $shopId,
                'customer_name'         => trim($request['customer_name']),
                'telephone'             => isset($request['telephone']) ? intval($request['telephone']) : '',
                'sex'                   => isset($request['sex']) ? intval($request['sex']) : 0,
                'age'                   => $age,
                'birthday'              => isset($request['birthday']) ? strtotime($request['birthday']) : '',
                'province'              => isset($request['province']) ? intval($request['province']) : 0,
                'city'                  => isset($request['city']) ? intval($request['city']) : 0,
                'region'                => isset($request['region']) ? intval($request['region']) : 0,
                'detailed_address'      => isset($request['detailed_address']) ? trim($request['detailed_address']) : '',
                'introducer'            => isset($request['introducer']) ? trim($request['introducer']) : '',
                'repair_progress'       => isset($request['repair_progress']) ? intval($request['repair_progress']) : 0,
                'effective_entry'       => $effective_entry,
                'first_time'            => $first_time,
                'second_time'           => $second_time,
                'status'                => isset($request['status']) ? intval($request['status']) : 2,
                'source_id'             => isset($request['source_id']) ? intval($request['source_id']) : 0,
                'nurse_id'             => isset($request['nurse_id']) ? intval($request['nurse_id']) : 0,
                'creator_id'            => $request['user_id'],
                // 'member_classification' => intval($request['member_classification']),
                'member_label'          => is_array($request['member_label']) && !empty($request['member_label']) ? implode(',',$request['member_label']) : '',
                'create_time'           => time(),
                'update_time'           => time(),
				'turn_customerid'       => $turn_customerid,
                'operator'              => $request['user_id'] ?? 0,
                'remarks'               => $request['remarks'] ?? '',
                'outreach_id'           => $request['outreach_id'] ?? 0,
                'difficulty_level'      => $request['difficulty_level'] ?? 0,
                'medical_source'        => $request['medical_source'] ?? 0,
                'source_type_id'        => isset($request['source_type_id']) ? intval($request['source_type_id']) : 0,
            ];
			//print_r($data);exit();
            $res = $this->where('telephone','=',$data['telephone'])->select()->toArray();
            if ($res) {
                if (count($res)>1) {
                   $yyshopInfo = Db::name('shop')->where('shop_id','=',$res[0]['shop_id'])->find();
                   $this->error = '手机号已存在无法创建客户，当前客户在【'.$yyshopInfo['shop_name'].'】门店';
                    return false;
                }
                $shopInfo = Db::name('shop')->where('shop_id','=',$shopId)->find();
                $yynfo = $res[0];
                $yyshopInfo = Db::name('shop')->where('shop_id','=',$yynfo['shop_id'])->find();
                //判断是否是需要添加第二份客户数据
                if($shopInfo['shop_type'] == 1 && $yyshopInfo['shop_type'] == 1){
                    $this->error = '手机号已存在无法创建客户，当前客户在【'.$yyshopInfo['shop_name'].'】门店';
                    return false;
                }
                if($shopInfo['shop_type'] == 2 && $yyshopInfo['shop_type'] == 2){
                    $this->error = '手机号已存在无法创建客户，当前客户在【'.$yyshopInfo['shop_name'].'】门店';
                    return false;
                }
            }
            $customerId = $this->insertGetId($data);
            // print_r($request['scar_type_position']);exit();
            if ($customerId) {
                // 疤痕问题关联
                $insertAll = [];
                foreach($request['scar_type_position'] as $key => $val) {
                    $value = [
                            'customer_setting_id_type'     => $val['type_id'],
                            'customer_setting_id_position' => $val['position_id'],
                            'customer_id'                  => $customerId
                        ];
                        $insertAll[] = $value;
                    // foreach ($val['position_id'] as $k => $v) {

                    // }
                }
                Db::name('customer_scar')->insertAll($insertAll);

                // 存储客户的余额信息
                $customer_balanceAll = [
                        [
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 1,
                        ],[
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 2,
                        ],[
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 3,
                        ],[
                            'shop_id'       => $shopId,
                            'customer_id'   => $customerId,
                            'balance_category_id'   => 4,
                        ]
                    ];
                $res = Db::name('customer_balance')->where('customer_id','=',$customerId)->select()->toArray();
                if(!$res){
                    Db::name('customer_balance')->insertAll($customer_balanceAll);
                }
                $this->error = '添加成功';
                return true;
            }
        // } catch (\Exception $e) {
        // }

        $this->error = '添加失败';
        return false;
    }

    /**
     * 编辑
     * @param  array $request 请求参数
     * @return bool
     */
    public function saveData(array $request): bool
    {
		//var_dump($request);var_dump('数据测试6865858');
        // try {
            $validate = new \app\crm\validate\Customer();

			if (!$validate->scene('update')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
            $customerId = intval($request['id']);
            $info       = $this->where('id', '=', $customerId)->find();
            if (!$info) {
                $this->error = '暂无客户数据';
                return false;
            }

            if (!isset($request['scar_type_position']) || !isset($request['scar_type_position'][0]['type_id']) || !isset($request['scar_type_position'][0]['position_id'])) {
                $this->error = '请选择疤痕类型和位置';
                return false;
            }

            $bool = true;
            foreach($request['scar_type_position'] as $key => $val) {
                if (!isset($val['type_id']) || !$val['type_id'] || !isset($val['position_id']) || !$val['position_id']) {
                    $bool = false;
                    break;
                }
            }

            if (!$bool) {
                $this->error = '请选择疤痕类型和位置';
                return false;
            }

			//新增一个 判断手机号 是不是存在
			$where = [];
			array_push($where,['id','=',$request['id']]);
			array_push($where,['shop_id','=',$request['shop_id']]);
			$now_res = Db::name('customer')->where($where)->select()->toArray();

			if($now_res[0]['telephone'] != $request['telephone']){
				$updatetelphone = $request['telephone'];
                //判断手机号是否已存在
                $where = [];
                array_push($where,['shop_id','=',$request['shop_id']]);
                $shop = Db::name('shop')->where($where)->find();
                if(!$shop)
                {
                    $this->error = '店铺不存在';
                    return false;
                }
                $where = [];
                array_push($where,['r.telephone','=',$updatetelphone]);
                array_push($where,['g.shop_type','=',$shop['shop_type']]);
                $telphoneExist = Db::name('customer')->alias('r')
                    ->join('shop g', 'r.shop_id=g.shop_id', 'LEFT')
                    ->where($where)->find();
                if(!empty($telphoneExist)){
                    $this->error = '手机号重复';
                    return false;
                }
			}else{
				$updatetelphone = $now_res[0]['telephone'];
			}
			// 新增一个
			$turnleng = strlen($request['turn_customerid']);

			if($turnleng == 11){
				$where = [];
				array_push($where,['telephone','=',$request['turn_customerid']]);
				array_push($where,['shop_id','=',$request['shop_id']]);
				$zhuanjies = Db::name('customer')->where($where)->select()->toArray();
				if(empty($zhuanjies)){
					$this->error = '该顾客不存在';
					return false;
				}else{
					$zcustomerId = $zhuanjies[0]['id'];
				}
			}else{
				if($request['turn_customerid']!=0){
					$zcustomerId = $request['turn_customerid'];
				}else{
					$zcustomerId = 0;
				}
			}

            $first_time = isset($request['first_time']) ? strtotime($request['first_time']) : '';
            $second_time = isset($request['second_time']) ? strtotime($request['second_time']) : '';
            //var_dump($first_time);
			if(empty($first_time) && empty($second_time)){
                $effective_entry = 0;
            }else if(empty($first_time) && !empty($second_time)){
                $this->error = '二次进店时间不为空，请录入首次进店时间';
                return false;
            }else{

                $effective_entry = 1;
				// /* 通过中台系统的进店时间 修改 同步触发 EC中的 客户进店状态---2022-07-16 */
				// $updatComeIn = new CustomerInfoAPIModel();
				// //查询改手机号是否再EC系统中
				// $ec_phone = $now_res[0]['telephone'];
				// $clientParam = $updatComeIn->lookcustomerId($ec_phone);
				// $clientListParam = json_decode($clientParam['result'],true);

                // echo "<pre>";
                // print_r($clientListParam);
                // echo "</pre>";
                // exit;

				// $clientInfo_y = $clientListParam['data'][0]['list'];
				// if(!empty($clientInfo_y)){
				// 	$dataLifo= [
				// 		'id'  => $request['id'],
				// 	];
				// 	$updatComeIn->updateCustomerT($dataLifo);
				// }
            }

            $shopId = intval($request['shop_id']);
            $age = 0;
            if (isset($request['birthday'])) {
            //     // code...
            //     strtotime($request['birthday']);

                $age     = bcsub(date('Y'),date('Y',strtotime($request['birthday'])));
            }

            $source_id =  isset($request['source_id']) ? intval($request['source_id']) : 0;
            $yes_update =[665,583,46,47,48,49];
            if(in_array($source_id,$yes_update)){
                $source_type_id=isset($request['source_type_id']) ? intval($request['source_type_id']) : 0;
                $insert = [
                    'customer_id'=>$request['id'],
                    'last_source_id'=>$info['source_id'],
                    'last_source_type_id'=>$info['source_type_id'],
                    'source_id'=>$source_id,
                    'source_type_id'=>$source_type_id,
                    'create_time'=>time(),
                    'operation_uid'=>$request['user_id']
                ];
                DB::name('customer_source_log')->insert($insert);
            }

            if($updatetelphone != $info['telephone']){
                $insert = [
                    'last_customer_phone'=>$info['telephone'],
                    'telephone'=>$updatetelphone,
                    'customer_id'=>$info['id'],
                    'operator_id'=>$request['user_id'],
                    'create_time'=>time(),
                ];
                DB::name('customer_info_change_log')->insert($insert);
            }


            $data = [
                'shop_id'            => $shopId,
                'customer_name'      => trim($request['customer_name']),
                'telephone'          => $updatetelphone,
                'sex'                => isset($request['sex']) ? intval($request['sex']) : 0,
                'age'                => $age,
                'birthday'           => isset($request['birthday']) ? strtotime($request['birthday']) : '',
                'province'           => isset($request['province']) ? intval($request['province']) : 0,
                'city'               => isset($request['city']) ? intval($request['city']) : 0,
                'region'             => isset($request['region']) ? intval($request['region']) : 0,
                'detailed_address'   => isset($request['detailed_address']) ? trim($request['detailed_address']) : '',
                'introducer'         => isset($request['introducer']) ? trim($request['introducer']) : '',
                // 'treatment_progress' => isset($request['treatment_progress']) ? intval($request['treatment_progress']) : 0,
                'effective_entry'    => $effective_entry,
                'first_time'         => $first_time,
                'second_time'        => $second_time,
                'status'             => isset($request['status']) ? intval($request['status']) : 2,
                'source_id'          => isset($request['source_id']) ? intval($request['source_id']) : 0,
                'source_type_id'          => isset($request['source_type_id']) ? intval($request['source_type_id']) : 0,
                'nurse_id'           => isset($request['nurse_id']) ? intval($request['nurse_id']) : 0,
                'member_classification'=> isset($request['member_classification']) ? intval($request['member_classification']) : 0,
                'member_label'       => is_array($request['member_label']) && !empty($request['member_label']) ? implode(',',$request['member_label']) : '',
                'creator_id'         => $request['user_id'],
                'update_time'        => time(),
                'remarks'            => $request['remarks'] ?? '',
				'turn_customerid'    => $zcustomerId ?? '',
                'outreach_id'        => $request['outreach_id'] ?? '',
                'repair_progress'    => $request['repair_progress'] ?? '',
                'difficulty_level'          => $request['difficulty_level'] ?? 0,
                'medical_source'            => $request['medical_source'] ?? 0,
            ];
			//var_dump($data);exit;
            !$info['first_time'] && $data['first_time'] = isset($request['first_time']) ? strtotime($request['first_time']) : '';
            !$info['second_time'] && $data['second_time'] = isset($request['second_time']) ? strtotime($request['second_time']) : '';
            $bool = $this->where(['id' => $customerId])->update($data);
            if ($bool) {
                // 疤痕问题关联
                $insertAll = [];
                $where = [
                    ['customer_id', '=', $customerId]
                ];
                Db::name('customer_scar')->where($where)->delete();
                foreach($request['scar_type_position'] as $key => $val) {
                    // foreach ($val['position_id'] as $k => $v) {
                        $value = [
                            'customer_setting_id_type'     => $val['type_id'],
                            'customer_setting_id_position' => $val['position_id'],
                            'customer_id'                  => $customerId
                        ];
                        $insertAll[] = $value;
                    // }
                }
                Db::name('customer_scar')->insertAll($insertAll);

                $this->error = '编辑成功';
                return true;
            }
        // } catch (\Exception $e) {
        // }

        $this->error = '编辑失败';
        return false;
    }


    /**
     * 更新进店时间
     * 更新转店状态
     */
    public function setCustomerStatus(array $request)
    {
        try {
            if (isset($request['customer_id']) && intval($request['customer_id']) <= 0) {
                // code...
                $this->error = '请选择需要设置的客户';
                return false;
            }
            $customer_id = Db::name('customer')->where('id','=',$request['customer_id'])->value('id');
            if (empty($customer_id)) {
                // code...
                $this->error = '当前客户不存在';
                return false;
            }
            $type            = isset($request['type']) ? intval($request['type']) : 0;
            if ($type == 0) {
                $this->error = '类型错误';
                return false;
            }else if ($type == 1) {// 更新进店时间
                // code...
                $saveData['new_join_shop_time']      = time();
            }else if ($type == 2) {// 更新转店状态
                // code...
                $saveData['turn_status']             = 2;
            }
            Db::name('customer')->where('id','=',$customer_id)->update($saveData);
            $this->error    = '更新成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '更新失败';
            return false;
        }
    }

    /**
     * 相册列表
     * @param  array $request 请求参数
     * @return bool
     */
    public function albumList(array $request): array
    {
        $customer_id = $request['customer_id'] ?? 0;

        $list = Db::name('customer_album')
                ->where('customer_id','=',$customer_id)
                ->select()
                ->toArray();
        $settingList    = Db::name('setting')->column('name', 'id');

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;
        $newList = [];
        foreach ($list as $key => $val){


            $newKey = $val['scar_type_id'].'-'.$val['more_id'].'-'.$val['cause_of_formation_id'];
            if(!isset($newList[$newKey])){

                $caseWhere = [];

                array_push($caseWhere,['customer_id','=',$customer_id]);
                array_push($caseWhere,['position_id','=',$val['more_id']]);
                array_push($caseWhere,['reason_id','=',$val['cause_of_formation_id']]);
                array_push($caseWhere,['type_id','=',$val['scar_type_id']]);
                array_push($caseWhere,['selection_results','in',[1,2,3]]);

                $caseRes = Db::name('case')->where($caseWhere)->order('id DESC')->find();

                // echo "<pre>";
                // print_r($caseRes);
                // echo "</pre>";

                $newList[$newKey]['scar_type_name'] = $settingList[$val['scar_type_id']] ?? '';
                $newList[$newKey]['more_name'] = $settingList[$val['more_id']] ?? '';
                $newList[$newKey]['cause_of_formation_name'] = $settingList[$val['cause_of_formation_id']] ?? '';
                $newList[$newKey]['list'] = [];
                $newList[$newKey]['id']   = $val['id'];
                $newList[$newKey]['haveBtn'] = $caseRes['selection_results'] ?? 'null' ;
                $newList[$newKey]['caseId'] = $caseRes['id'] ?? '' ;
            }
            $one = [
                    'id'=>$val['id'],
                    'src'=>$val['src'],
                    'create_time'=>date('Y-m-d H:i:s',$val['create_time'])
                    ];
            array_push($newList[$newKey]['list'],$one);
            // array_push($newList[$newKey]['list'],[$val['src']]);
        }

        // exit;
        $newList = array_values($newList);
        return ['list'=>$newList];
    }

    /**
     * 新增相片
     * @param  array $request 请求参数
     * @return bool
     */
    public function addAlbum(array $request): bool
    {
        try{
            $addData['create_time']  = time();
            $addData['user_id']      = $request['user_id'] ?? '';
            $addData['shop_id']      = $request['shop_id'] ?? 0;
            $addData['customer_id']  = $request['customer_id'] ?? 0;
            $addData['scar_type_id'] = $request['scar_type_id'] ?? 0;
            $addData['more_id']      = $request['more_id'] ?? 0;
            $addData['cause_of_formation_id'] = $request['cause_of_formation_id'] ?? 0;

            if(empty($addData['scar_type_id'])){
                $this->error = '请选择上传的照片的疤痕类型';
                return false;
            }
            if(empty($addData['more_id'])){
                $this->error = '请选择上传的照片的疤痕部位';
                return false;
            }
            if(empty($addData['cause_of_formation_id'])){
                $this->error = '请选择上传的照片的疤痕的形成原因';
                return false;
            }
            $src = $request['src'] ?? '';
            if(is_array($src)){
                foreach ($src as $key => $val){
                    if(empty($src)){
                        $this->error = '请选择上传的照片';
                        return false;
                    }
                }
                foreach ($src as $key => $val){
                    $addData['src']          = $val;
                    $id = Db::name('customer_album')->insertGetId($addData);
                }
            }else{
                if(empty($src)){
                    $this->error = '请选择上传的照片';
                    return false;
                }
                $addData['src']          = $src;
                $id = Db::name('customer_album')->insertGetId($addData);
            }

            $this->error    = '添加成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '添加失败';
            return false;
        }
    }

    /**
     * 删除相片
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteAlbum(array $request): bool
    {
        try{
            $id = $request['id'] ?? 0;
            if(!$id){
               $this->error    = '请选择删除的照片';
                return false;
            }
            Db::name('customer_album')->where('id','=',$id)->delete();
            $this->error    = '删除成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '删除失败';
            return false;
        }
    }

    /**
     * 删除案例治疗记录照片
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteCaseLogImg(array $request): bool
    {

        try{
            $id = $request['id'] ?? 0;
            $key = $request['key'] ?? '';

            if(!$id){
                $this->error    = '请选择删除的照片';
                return false;
            }

            // if(empty($key)){
            //     $this->error    = '删除为空，请重新操作';
            //     return false;
            // }

            $tagLog = Db::name('case_log')->where('id','=',$id)->find();
            $images = explode(',',$tagLog['images']);

            unset($images[$key]);

            $newImages = implode(',',$images);

            Db::name('case_log')->where('id','=',$id)->update(['images' => $newImages]);

            $this->error    = '删除成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '删除失败';
            return false;
        }
    }

    /***
     * 客户余额的处理
     * $customer_id     客户的id
     * $balanceData [   余额变更数据集
     *     change_type     变动类型 1:增加 2:减少
     *     change_money    变更的本金
     *     complimentary_money  变更的赠金
     *     balance_category_id  变更的余额的类型 1:疤痕 2:项目
     * ]
     * $newOrderData[   新单变更数据集
     *      cj_time     成交时间-时间戳
     *      cj_money    成交金额
     *      cj_order_id 成交的订单单号
     * ]
     * $orderInfo[       本次需要新增的订单金额
     *      order_amount 本次订单金额
     *      order_time   本次订单的时间-时间戳
     * ]
     * $member_products  购买了几次会员商品
     * $yhjOrderInfo[    本次需要处理的优惠卷
     *      yhj_id       本次优惠卷的id
     *      order_id     本次订单的id
     *      operator_id  核销人的id
     * ]
     */
    public function processingFunds($customer_id=0,array $balanceData=array(),$deal_time=0,array $newOrderData=array(),array $orderInfo = array(),array $yhjOrderInfo=array(),$member_products=0): bool
    {

        // echo "顾客id:".$customer_id;
        // echo "<br/>";

        // echo "<pre>";
        // print_r($balanceData);

        // exit;


        $date_array = [];
        if($deal_time>0){
            // 单据结算日期
            $start_time = date('Ymd',strtotime($deal_time));

            // 当前日期
            $today_time = date('Ymd');


            $sub_num = bcsub($today_time,$start_time,0);


            for($i=0;$i<=$sub_num;$i++){
                $str = date('Ymd',strtotime('-'.$i.' day'));

                array_push($date_array,$str);
            }
        }

        // echo "<pre>";
        // print_r($date_array);

        // exit;


        // try{
            $customerIdWhere = [];
            array_push($customerIdWhere,['id','=',$customer_id]);
            $customerInfo = Db::name('customer')->where($customerIdWhere)->find();

            // 余额和本金的处理
            if (!$customerInfo) {
                // 没有查询到客户的数据
                $this->error    = '客户数据不存在';
                return false;
            }
            $cSaveData = [];
            if(!empty($balanceData)){
            $change_type  = $balanceData['change_type'] ?? 0;
            foreach($balanceData['changeData'] as $key=>$v){
                $change_money = $v['change_money'] ?? 0;
                $complimentary_money = $v['complimentary_money'] ?? 0;
                $shop_transfer_money = $v['shop_transfer_money'] ?? 0;
                $balance_category_id = $v['balance_category_id'] ?? 0;
                $balanceWhere = [];
                array_push($balanceWhere,['customer_id','=',$customer_id]);
                array_push($balanceWhere,['balance_category_id','=',$v['balance_category_id']]);
                $balanceInfo  = Db::name('customer_balance')->where($balanceWhere)->find();
                if (in_array($change_type,[1,2]) && !empty($balanceInfo) && !empty($date_array)) {
                    $change_money        = abs($v['change_money']);
                    $complimentary_money = abs($v['complimentary_money']);
                    $shop_transfer_money = abs($v['shop_transfer_money']);
                    $balanceSaveData     = [];
                    if ($change_type == 1) {
                        // code...
                        $balanceSaveData['money'] = bcadd($balanceInfo['money'],$change_money,2);
                        $balanceSaveData['complimentary_money'] = bcadd($balanceInfo['complimentary_money'],$complimentary_money,2);
                        $balanceSaveData['shop_transfer_money'] = bcadd($balanceInfo['shop_transfer_money'],$shop_transfer_money,2);
                    }else{
                        $balanceSaveData['money'] = bcsub($balanceInfo['money'],$change_money,2);
                        $balanceSaveData['complimentary_money'] = bcsub($balanceInfo['complimentary_money'],$complimentary_money,2);
                        $balanceSaveData['shop_transfer_money'] = bcsub($balanceInfo['shop_transfer_money'],$shop_transfer_money,2);
                    }
                    Db::name('customer_balance')->where($balanceWhere)->update($balanceSaveData);

                    if($date_array){
                        foreach ($date_array as $key => $value) {
                            $balance_tj_where = [];
                            array_push($balance_tj_where,['customer_id','=',$customer_id]);
                            array_push($balance_tj_where,['balance_category_id','=',$v['balance_category_id']]);
                            array_push($balance_tj_where,['time','=',$value]);
                            $balance_tj_info  = Db::name('customer_balance_tj')->where($balance_tj_where)->find();

                            if (in_array($change_type,[1,2]) && !empty($balance_tj_info)) {
                                $balanceTjSaveData     = [];
                                if ($change_type == 1) {
                                    $balanceTjSaveData['money'] = bcadd($balance_tj_info['money'],$change_money,2);
                                    $balanceTjSaveData['complimentary_money'] = bcadd($balance_tj_info['complimentary_money'],$complimentary_money,2);
//                                    $balanceTjSaveData['shop_transfer_money'] = bcadd($balance_tj_info['shop_transfer_money'],$shop_transfer_money,2);
                                }else{
                                    $balanceTjSaveData['money'] = bcsub($balance_tj_info['money'],$change_money,2);
                                    $balanceTjSaveData['complimentary_money'] = bcsub($balance_tj_info['complimentary_money'],$complimentary_money,2);
//                                    $balanceTjSaveData['shop_transfer_money'] = bcsub($balance_tj_info['shop_transfer_money'],$shop_transfer_money,2);
                                }
                                // 修改customer_balance_tj表格
                                Db::name('customer_balance_tj')->where($balance_tj_where)->update($balanceTjSaveData);
                            }
                        }
                    }
                }
            }
        }
            // 优惠劵的核销处理
            $yhj_id = $yhjOrderInfo['yhj_id'] ?? 0;
            if ($yhj_id > 0){
                $yhjSave             = [];
                $yhjSave['use_time'] = time();
                $yhjSave['staus']    = 1;
                $yhjSave['order_id'] = $yhjOrderInfo['order_id'] ?? 0;
                $yhjSave['order_sn'] = $yhjOrderInfo['order_sn'] ?? '';
                $yhjSave['user_id']  = $yhjOrderInfo['operator_id'] ?? 0;
                Db::name('coupon_provide_customer')->where('id','=',$yhj_id)->update($yhjSave);
            }
            $customerSaveData = [];
            // // 新单的处理

			if(!empty($newOrderData['cj_type'])){
				// 新单 作废 触发清空 新单的时间和金额 以及订单
				if($newOrderData['cj_order_id'] == $customerInfo['cj_order_id'] && $newOrderData['cj_type'] ==1){
					$cjSaveData             = [];
					$cjSaveData['cj_time']     = 0;
					$cjSaveData['cj_money']    = 0;
					$cjSaveData['cj_order_id'] = 0;

					Db::name('customer')->where('id','=',$customer_id)->update($cjSaveData);
				}

			}else{
				// 新单 新增触发 改变顾客的 新单时间和 金额的
				if($customerInfo['cj_time']==0 && !empty($newOrderData)){
				    $cj_time     = $newOrderData['cj_time'] ?? 0;
				    $cj_money    = $newOrderData['cj_money'] ?? 0;
				    $cj_order_id = $newOrderData['cj_order_id'] ?? 0;
				    if ($cj_time>0 && $cj_money>0 && $cj_order_id>0) {
				        // 新单数据的存储
				        $customerSaveData['cj_time']     = $cj_time;
				        $customerSaveData['cj_money']    = $cj_money;
				        $customerSaveData['cj_order_id'] = $cj_order_id;
				    }
				}
			}

			//转介绍顾客的新单数据处理----2022.04.19
			$customerSaveTurnData = [];
			if($customerInfo['turn_cjtime']==0 && !empty($newOrderData)){
				$turn_cjtime     = $newOrderData['turn_cjtime'] ?? 0;
				$turn_cjmoney    = $newOrderData['turn_cjmoney'] ?? 0;
				$turn_order_id   = $newOrderData['turn_order_id'] ?? 0;
				if ($turn_cjtime>0 && $turn_cjmoney>0 && $turn_order_id>0) {
				    // 新单数据的存储
				    $customerSaveTurnData['turn_cjtime']     = $turn_cjtime;
				    $customerSaveTurnData['turn_cjmoney']    = $turn_cjmoney;
				    $customerSaveTurnData['turn_order_id']   = $turn_order_id;
				}

				if(!empty($customerSaveTurnData)){
				    Db::name('customer')->where('id','=',$customerInfo['turn_customerid'])->update($customerSaveTurnData);
				}
			}

            // // 累计消费金额的处理
             $consumption = $customerInfo['consumption'];
//            $consumption = Db::name('customer')->where('telephone','=',$customerInfo['telephone'])->where('status','=',1)->sum('consumption');
            if(!empty($orderInfo)){
                $order_time = $orderInfo['order_time'] ?? 0;
                if($order_time>0){
                    $order_amount = $orderInfo['order_amount'] ?? 0;
                    $consumption  = bcadd($consumption,$order_amount,2);
                    $customerSaveData['consumption']       = $consumption;
                    // $customerSaveData['final_consumption'] = $order_time;
                    // $customerSaveData['final_consumption_money'] = $order_amount;
                }
            }

            // case $consumption >= 1 && $consumption < 5000:   // D类客户
            // // 客户分类的处理
            // // 更新客户会员等级
            $membership_leve = 0;
            if ($consumption != $customerInfo['consumption']) { // 当累计消费金额和原来不一样的时候
                // 处理客户分类
                switch ($consumption)
                {
                    case $consumption >= 50000: // A类客户
                        $customerSaveData['member_classification'] = 73;
                        break;
                    case $consumption >= 15000: // B类客户
                    // case $consumption < 50000:
                        $customerSaveData['member_classification'] = 72;
                        break;
                    case $consumption >= 5000: // C类客户
                    // case $consumption < 15000:
                        $customerSaveData['member_classification'] = 71;
                        break;
                    case $consumption >= 1:    // D类客户
                    // case $consumption < 5000:
                        $customerSaveData['member_classification'] = 70;
                        break;
                    default:
                        break;


                }

            }

            // 处理客户应该是哪个级别的会员
            $customerGradeList = Db::name('customer_grade')->select()->toArray();
            foreach($customerGradeList as $key => $val){
                if ($val['maximum']==0 && $val['minimum']<=$consumption) {//当时最后一级时,大于初始金额即可设置为该等级
                    // code...
                    $membership_leve = $val['id'];
                }else if($val['maximum']>=$consumption && $val['minimum']<=$consumption){
                    $membership_leve = $val['id'];
                }
            }

            // 处理客户会员的过期时间
            $member_products = is_numeric($member_products)?intval($member_products):0;
            // $member_products = bcadd($member_products,$customerInfo['member_products']);

            // echo "<pre>";
            // print_r($member_products);
            // echo "</pre>";
            // exit;

            $oneYear = 31536000;

            if($member_products>0){

                if ($customerInfo['join_time'] == 0) {
                    $join_time = time();

                    $be_overdue_time = bcmul($oneYear,$member_products);
                    $be_overdue_time = bcadd($be_overdue_time, $join_time);
                }else{

                    if($customerInfo['be_overdue_time'] > time()){
                        $join_time = $customerInfo['join_time'];

                        $be_overdue_time = bcmul($oneYear,$member_products);
                        $be_overdue_time = bcadd($be_overdue_time, $customerInfo['be_overdue_time']);
                    }else{
                        $join_time = time();

                        $be_overdue_time = bcmul($oneYear,$member_products);
                        $be_overdue_time = bcadd($be_overdue_time, $join_time);
                    }

                }

                // $be_overdue_time = bcmul($oneYear,$member_products);
                // $be_overdue_time = bcadd($be_overdue_time, $join_time);
                $customerSaveData['join_time'] = $join_time;
                $customerSaveData['be_overdue_time'] = $be_overdue_time;
                $customerSaveData['member_products'] = $member_products;
                $customerSaveData['membership_leve'] = $membership_leve;

            }

            // echo "<pre>";
            // print_r($customerSaveData);
            // exit;
            // 更新客户数据
            if(!empty($customerSaveData)){
                Db::name('customer')->where($customerIdWhere)->update($customerSaveData);
            }
            return true;
        // } catch (\Exception $e) {
        //     $this->error    = '余额变更失败';
        //     return false;
        // }
    }

    /**
     * 增加客户的服务

     */
    public function addCustomService($customer_id,$serviceDataAll):bool
    {
        try{
            $addAll = [];
            foreach($serviceDataAll as $key => $value){
                $addData['order_id']    = $value['order_id'] ?? '';  //订单id
                $addData['name']    = $value['name'] ?? '';  //服务名称
                $addData['num']     = $value['num'] ?? 0;   // 必填--服务类型：1按期2按次
                $addData['shop_id'] = $value['shop_id'] ?? 0;    // 店铺id
                $addData['customer_id']  = $value['customer_id'] ?? 0;   // 必填--客户id
                $addData['service_type'] = $value['service_type'] ?? 2;   // 必填--服务类型：1按期2按次
                $addData['start_time']   = $value['start_time'] ?? '';    // 类型为1是必填--服务开始时间
                $addData['end_time']     = $value['end_time'] ?? '';      // 类型为1是必填--服务开始时间
                $addData['experience']   = $value['experience'] ?? 0;     // 0否1是 是否体验
                $addData['kk_user_id']   = $value['kk_user_id'] ?? 0;     // 开卡人id
                $addData['kk_money']     = $value['kk_money'] ?? 0;       // 开卡金额
                $addData['create_time']  = time();     // 创建时间
                $addData['goods_id']     = $value['goods_id'] ?? 0;     // 创建时间
                $addData['category_id']  = $value['category_id'] ?? 0;      // 创建时间

                $addData['consume_store_transfer']  = $value['consume_store_transfer'] ?? 0;      // 消耗的店转
                $addData['consume_gratuity']  = $value['consume_gratuity'] ?? 0;      // 消耗的赠金
                $addData['consume_money']  = $value['consume_money'] ?? 0;      // 消耗的本金
                $addData['service_max_num']  = $value['service_max_num'] ?? 0;      // 总最高进店次数

                $addData['first_month_max_service_num']  = $value['first_month_max_service_num'] ?? 0;      // 首次
                $addData['middle_month_max_service_num']  = $value['middle_month_max_service_num'] ?? 0;      // 中间
                $addData['end_month_max_service_num']  = $value['end_month_max_service_num'] ?? 0;      // 结尾

                $addData['status'] = 1;
                if($addData['service_type'] == 1 && $addData['end_time']<=time()){
                    $addData['status'] = 2;
                }else{
                    if ($addData['num']==0) {
                        $addData['status'] = 1;
                    }
                }
                array_push($addAll,$addData);
            }

            $res = Db::name('service')->insertAll($addAll);
//            var_dump($res);die;
            return true;
        } catch (\Exception $e) {
            $this->error    = '服务添加失败';
            return false;
        }
    }

    // 客户资料推送金蝶
    public function pushKingCustomer($customer_id): bool
    {

        $customerInfo = Db::name('customer')->where('id','=',$customer_id)->find();
        $shopInfo = Db::name('shop')->where('shop_id','=',$customerInfo['shop_id'])->find();

        if(!$customerInfo || !$shopInfo || $shopInfo['type'] == 2){
            $this->error    = '店铺客户数据异常';
            return false;
        }
        if(empty($shopInfo['market_kingdee_code']) || empty($shopInfo['keycode'])){
            $this->error    = '店铺金蝶编码异常';
            return false;
        }
        if(!empty($customerInfo['fcustId']) && !empty($customerInfo['king_no'])){
            $this->error    = '客户金蝶资料已存在';
            return true;
        }

        $kingData = [
                'king_no'       => $customerInfo['king_no'],
                'fcustId'       => $customerInfo['fcustId'] ?? 0,
                'customer_name' => $customerInfo['customer_name'],
                'sale_no'       => $shopInfo['market_kingdee_code'],
                'shop_no'       => $shopInfo['keycode'],
                'shop_id'       => $shopInfo['shop_id'],
                'customer_id'       => $customer_id,
            ];

        // 推送资料
        $kingdee = new \Kingdee\Kingdee();
        $res = $kingdee->add_customer($kingData);

        if ($res === true){
            // 提交客户资料
            $customerInfo = Db::name('customer')->where('id','=',$customer_id)->find();
            $subData = [
                    'fcustId'     => $customerInfo['fcustId'],
                    'customer_id' => $customer_id,
                ];
            $res = $kingdee->submit_customer($subData);
            if ($res !== true){
                $msg = $res === false?'客户资料推送失败':$res;
                $this->error = $msg;
                return false;
            }
            $auditData = [
                    'fcustId'     => $customerInfo['fcustId'],
                    'customer_id' => $customer_id,
                ];
            $res = $kingdee->audit_customer($auditData);
            if ($res !== true){
                $msg = $res === false?'客户资料推送失败':$res;
                $this->error = $msg;
                return false;
            }
            // 审核客户资料
            return true;
        }else{
            $msg = $res === false?'客户资料推送失败':$res;
            $this->error = $msg;
            return false;
        }
    }
    /**
     * 获取黄v数据
     */
    public function getYellowV($request):array
    {
        $staffIds = [550,945,1026];
        $shopId = '73782774881835';//中医院
        $staff = Db::name('admin_user')->field('id,realname')->where('id','in',$staffIds)->select()->toArray();
        $data = [];
        foreach($staff as $value)
        {
            $data[$value['id']]['name']=$value['realname'];
            $data[$value['id']]['id']=$value['id'];
        }
        $baseWhere = [];
        array_push($baseWhere,['a.operator','in',$staffIds]);
        array_push($baseWhere,['a.shop_id','=',$shopId]);
        array_push($baseWhere,['a.nurse_id','<>',0]);
        array_push($baseWhere,['a.create_time','>=',strtotime($request['start_time'])]);
        array_push($baseWhere,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);
        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        //预约线上
        $reservationConsultation = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($baseWhere)
            ->where($where)
            ->group('a.operator')
            ->select()->toArray();


        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        //预约到院
        $reservationReach = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($baseWhere)
            ->where($where)
            ->group('a.operator')
            ->select()->toArray();

        foreach($reservationConsultation as $value)
        {
            $data[$value['operator_id']]['reservationConsultation']=$value['count'];
            $data[$value['operator_id']]['id']=$value['operator_id'];
        }
        foreach($reservationReach as $value)
        {
            $data[$value['operator_id']]['reservationReach']=$value['count'];
        }

        $baseWhere2 = [];
        array_push($baseWhere2,['a.operator','in',$staffIds]);
        array_push($baseWhere2,['a.shop_id','=',$shopId]);
        array_push($baseWhere2,['a.nurse_id','<>',0]);


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        $orWhere=[];
        array_push($orWhere,['b.reach_first_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        array_push($orWhere,['b.reach_second_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        //实际线上
        $realReservationConsultation = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($where)
            ->where($baseWhere2)
            ->where(function($query)use($orWhere){
                $query->whereOr($orWhere);
            })
            ->group('a.operator')
            ->select()->toArray();

        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        $orWhere=[];
        array_push($orWhere,['b.consultation_first_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        array_push($orWhere,['b.consultation_second_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        //实际到院
        $realReservationReach = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($where)
            ->where($baseWhere2)
            ->whereOr(function($query)use($orWhere){
                $query->whereOr($orWhere);
            })
            ->group('a.operator')
            ->select()->toArray();


        foreach($realReservationConsultation as $value)
        {
            $data[$value['operator_id']]['realReservationConsultation']=$value['count'];
        }
        foreach($realReservationReach as $value)
        {
            $data[$value['operator_id']]['realReservationReach']=$value['count'];
        }
        // print_r($data);
        // exit;
        // $data['reservationSum'] = $data['reservationConsultation']+$data['reservationReach'];

        $where = [];
        array_push($baseWhere2,['c.status','=',2]);
        array_push($baseWhere2,['c.type','=',3]);
        array_push($baseWhere2,['c.deal_time','>=',strtotime($request['start_time'])]);
        array_push($baseWhere2,['c.deal_time','<',strtotime($request['end_time'])+24*60*60]);


        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',1]);
        //看诊成交
        $dealConsultation = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,count(distinct uid) as count');


        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',1]);
        //到院成交
        $dealReach = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,count(distinct uid) as count');

        foreach($dealConsultation as $value)
        {
            $data[$value['operator_id']]['dealConsultation']=$value['count'];
        }
        foreach($dealReach as $value)
        {
            $data[$value['operator_id']]['dealReach']=$value['count'];
        }


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',1]);
        //线上成交新单金额
        $dealConsultationNew = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');
        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',1]);
        //到院成交新单金额
        $dealReachNew = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        foreach($dealConsultationNew as $value)
        {
            $data[$value['operator_id']]['dealConsultationNew']=$value['sum'];
        }
        foreach($dealReachNew as $value)
        {
            $data[$value['operator_id']]['dealReachNew']=$value['sum'];
        }


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',2]);
        //线上成交补单金额
        $dealConsultationOld = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',2]);
        //到院成交补单金额
        $dealReachOld = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        foreach($dealConsultationOld as $value)
        {
            $data[$value['operator_id']]['dealConsultationOld']=$value['sum'];
        }
        foreach($dealReachOld as $value)
        {
            $data[$value['operator_id']]['dealReachOld']=$value['sum'];
        }
        // print_r($data);
        // exit;
        foreach($data as $key => $value)
        {
            if(empty($value['id']))
                {
                    unset($data[$key]);
                    continue;
                }
            if(empty($value['realReservationConsultation']))
                $data[$key]['realReservationConsultation']=0;
            if(empty($value['realReservationReach']))
                $data[$key]['realReservationReach']=0;

            if(empty($value['dealConsultation']))
                $data[$key]['dealConsultation']=0;
            if(empty($value['dealReach']))
                $data[$key]['dealReach']=0;

            if(empty($value['reservationConsultation']))
            {
                $data[$key]['reservationConsultation']=0;
                $data[$key]['reservationConsultationRate']=0;
            }else{
                $data[$key]['reservationConsultationRate']=number_format($data[$key]['dealConsultation']/$data[$key]['reservationConsultation'], 2)*100;
            }
            $data[$key]['reservationConsultationRate'].='%';
            if(empty($value['reservationReach']))
            {
                $data[$key]['reservationReach']=0;
                $data[$key]['reservationReachRate']=0;
            }else{
                $data[$key]['reservationReachRate']=number_format($data[$key]['dealReach']/$data[$key]['reservationReach'], 2)*100;
            }
            $data[$key]['reservationReachRate'].='%';
            $data[$key]['reservationSum'] = $data[$key]['reservationConsultation']+$data[$key]['reservationReach'];
            if(empty($value['reservationConsultation'])&&empty($value['reservationReach']))
            {
                $data[$key]['sumRate']=0;
            }else{
                $data[$key]['sumRate']=number_format(($data[$key]['dealConsultation']+$data[$key]['dealReach'])/($data[$key]['reservationConsultation']+$data[$key]['reservationReach']), 2)*100;
            }
            $data[$key]['sumRate'].='%';
            if(empty($value['dealConsultationNew']))
                $data[$key]['dealConsultationNew']=0;
            if(empty($value['dealReachNew']))
                $data[$key]['dealReachNew']=0;
            if(empty($value['dealConsultationOld']))
                $data[$key]['dealConsultationOld']=0;
            if(empty($value['dealReachOld']))
                $data[$key]['dealReachOld']=0;
            $data[$key]['newSum']=$data[$key]['dealConsultationNew']+$data[$key]['dealReachNew'];
            $data[$key]['oldSum']=$data[$key]['dealConsultationOld']+$data[$key]['dealReachOld'];
            $data[$key]['sum']=number_format($data[$key]['newSum']+$data[$key]['oldSum'],2);
        }
        $data = array_merge($data,[]);
        // print_r($data);
        // exit;
        return $data;

    }

    /**
     * 黄v客服详情页数据
     */
    public function getYellowVService($request)
    {
        $staffId = $request['id'];
        $staffIds = [550,945,1026];
        $shopId = '73782774881835';//中医院
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.create_time','>',strtotime($request['start_time'])]);
        array_push($where,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);
        $data = Db::name('customer')->alias('a')
        ->join('shop_person b','b.id = a.nurse_id','left')
        ->join('customer_extra c','c.customer_id = a.id','left')
        ->field('c.consultation_status,b.id,b.name,count(*) as count')
        ->where($where)->group('a.nurse_id,c.consultation_status')->select()->toArray();
        $where = [];
        array_push($where,['a.operator','in',$staffIds]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.shop_id','=',$shopId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        // array_push($where,['b.position_id','in',[8,9,10]]);
        $physician = Db::name('customer')->alias('a')
        ->join('shop_person b','b.id = a.nurse_id','right')
        ->join('customer_extra c','c.customer_id = a.id','left')
        ->field('b.id,b.name')
        ->where($where)->group('a.nurse_id')->select()->toArray();
        $dataTwo=[];
        foreach($data as $value)
        {
            $dataTwo[$value['id']][$value['consultation_status']]=$value;
        }
        $result = [];
        foreach($physician as $key=>$value)
        {
            $result[$key]['consultation'] = $dataTwo[$value['id']][1]['count']??0;
            $result[$key]['reach'] = $dataTwo[$value['id']][2]['count']??0;
            $result[$key]['name'] = $value['name'];
            $result[$key]['sum'] = $result[$key]['consultation']+$result[$key]['reach'];
        }
        return $result;
    }
    /**
     * 黄v护理师详情页
     */
    public function getYellowVPhysician($request):array
    {
        $staffId = $request['id'];
        // $staffIds = [550,945,940];
        $consultation_status = $request['consultation_status'];
        $shopId = '73782774881835';//中医院
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.shop_id','=',$shopId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        // array_push($where,['b.position_id','in',[8,9]]);
        $physician = Db::name('customer')->alias('a')
            ->join('shop_person b','b.id = a.nurse_id','right')
            ->join('customer_extra c','c.customer_id = a.id','left')
            ->field('b.id,b.name')
            ->where($where)->group('a.nurse_id')->select()->toArray();
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['b.consultation_status','=',$consultation_status]);
        array_push($where,['a.create_time','>',strtotime($request['start_time'])]);
        array_push($where,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);

        $number = Db::name('customer')->alias('a')
            ->join('customer_extra b','b.customer_id = a.id','left')
            ->field('a.nurse_id,count(*) as count')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();
        array_push($where,['c.status','=',2]);
        array_push($where,['c.type','=',3]);

        $deal = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','c.uid = b.customer_id','left')
            ->field('a.nurse_id,count(distinct uid) as count')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();

        $dealMoney = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','c.uid = b.customer_id','left')
            ->field('a.nurse_id,sum(pay_amount) as sum')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();
        $numberData=[];
        foreach($number as $value)
        {
            $numberData[$value['nurse_id']]=$value['count'];
        }
        $dealData=[];
        foreach($deal as $value)
        {
            $dealData[$value['nurse_id']]=$value['count'];
        }
        $dealMoneyData=[];
        foreach($dealMoney as $value)
        {
            $dealMoneyData[$value['nurse_id']]=$value['sum'];
        }
        $result = [];
        foreach($physician as $key =>$value)
        {
            $result[$key]['name']=$value['name'];
            if(empty($numberData[$value['id']]))
            {
                $result[$key]['number'] = 0;
            }else{
                $result[$key]['number'] = $numberData[$value['id']];
            }
            if(empty($dealData[$value['id']]))
            {
                $result[$key]['deal'] = 0;
            }else{
                $result[$key]['deal'] = $dealData[$value['id']];
            }
            if(empty($dealMoneyData[$value['id']]))
            {
                $result[$key]['dealMoney'] = 0;
            }else{
                $result[$key]['dealMoney'] = $dealMoneyData[$value['id']];
            }
            if(empty($result[$key]['number']))
            {
                $result[$key]['dealRate']=0;
            }else{
                $result[$key]['dealRate']=number_format($result[$key]['deal']/$result[$key]['number'],2);
            }
            if(empty($result[$key]['deal']))
            {
                $result[$key]['avg']=0;
            }else{
                $result[$key]['avg']=number_format($result[$key]['dealMoney']/$result[$key]['deal'],2);
            }

        }
        return $result;

    }
    /**
     * sql统一处理
     */
    public function reckon($where,$field)
    {
        return Db::name('customer')->alias('a')
        ->join('customer_extra b','a.id = b.customer_id','left')
        ->join('shop_refund_order c','c.uid = b.customer_id','left')
        ->field($field)
        ->where($where)
        ->group('a.operator')
        ->select()->toArray();
    }
}
